|
6 | 6 | # --------------------------------------------------------------------------
|
7 | 7 | import base64
|
8 | 8 | from json import JSONEncoder
|
9 |
| -from typing import Union, cast, Any |
| 9 | +from typing import Dict, Optional, Union, cast, Any |
10 | 10 | from datetime import datetime, date, time, timedelta
|
11 | 11 | from datetime import timezone
|
12 | 12 |
|
@@ -140,3 +140,111 @@ def is_generated_model(obj: Any) -> bool:
|
140 | 140 | :rtype: bool
|
141 | 141 | """
|
142 | 142 | return bool(getattr(obj, "_is_model", False) or hasattr(obj, "_attribute_map"))
|
| 143 | + |
| 144 | + |
| 145 | +def _is_readonly(p: Any) -> bool: |
| 146 | + """Check if an attribute is readonly. |
| 147 | +
|
| 148 | + :param any p: The property to check. |
| 149 | + :return: True if the property is readonly, False otherwise. |
| 150 | + :rtype: bool |
| 151 | + """ |
| 152 | + try: |
| 153 | + return p._visibility == ["read"] # pylint: disable=protected-access |
| 154 | + except AttributeError: |
| 155 | + return False |
| 156 | + |
| 157 | + |
| 158 | +def _as_attribute_dict_value(v: Any, *, exclude_readonly: bool = False) -> Any: |
| 159 | + if v is None or isinstance(v, _Null): |
| 160 | + return None |
| 161 | + if isinstance(v, (list, tuple, set)): |
| 162 | + return type(v)(_as_attribute_dict_value(x, exclude_readonly=exclude_readonly) for x in v) |
| 163 | + if isinstance(v, dict): |
| 164 | + return {dk: _as_attribute_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} |
| 165 | + return as_attribute_dict(v, exclude_readonly=exclude_readonly) if is_generated_model(v) else v |
| 166 | + |
| 167 | + |
| 168 | +def _get_flattened_attribute(obj: Any) -> Optional[str]: |
| 169 | + flattened_items = None |
| 170 | + try: |
| 171 | + flattened_items = getattr(obj, next(a for a in dir(obj) if "__flattened_items" in a), None) |
| 172 | + except StopIteration: |
| 173 | + return None |
| 174 | + |
| 175 | + if flattened_items is None: |
| 176 | + return None |
| 177 | + |
| 178 | + for k, v in obj._attr_to_rest_field.items(): # pylint: disable=protected-access |
| 179 | + try: |
| 180 | + if set(v._class_type._attr_to_rest_field.keys()).intersection( # pylint: disable=protected-access |
| 181 | + set(flattened_items) |
| 182 | + ): |
| 183 | + return k |
| 184 | + except AttributeError: |
| 185 | + # if the attribute does not have _class_type, it is not a typespec generated model |
| 186 | + continue |
| 187 | + return None |
| 188 | + |
| 189 | + |
| 190 | +def as_attribute_dict(obj: Any, *, exclude_readonly: bool = False) -> Dict[str, Any]: |
| 191 | + """Convert an object to a dictionary of its attributes. |
| 192 | +
|
| 193 | + Made solely for backcompatibility with the legacy `.as_dict()` on msrest models. |
| 194 | +
|
| 195 | + .. deprecated::1.35.0 |
| 196 | + This function is added for backcompat purposes only. |
| 197 | +
|
| 198 | + :param any obj: The object to convert to a dictionary |
| 199 | + :keyword bool exclude_readonly: Whether to exclude readonly properties |
| 200 | + :return: A dictionary containing the object's attributes |
| 201 | + :rtype: dict[str, any] |
| 202 | + :raises TypeError: If the object is not a generated model instance |
| 203 | + """ |
| 204 | + if not is_generated_model(obj): |
| 205 | + raise TypeError("Object must be a generated model instance.") |
| 206 | + if hasattr(obj, "_attribute_map"): |
| 207 | + # msrest generated model |
| 208 | + return obj.as_dict(keep_readonly=not exclude_readonly) |
| 209 | + try: |
| 210 | + # now we're a typespec generated model |
| 211 | + result = {} |
| 212 | + readonly_props = set() |
| 213 | + |
| 214 | + # create a reverse mapping from rest field name to attribute name |
| 215 | + rest_to_attr = {} |
| 216 | + flattened_attribute = _get_flattened_attribute(obj) |
| 217 | + for attr_name, rest_field in obj._attr_to_rest_field.items(): # pylint: disable=protected-access |
| 218 | + |
| 219 | + if exclude_readonly and _is_readonly(rest_field): |
| 220 | + # if we're excluding readonly properties, we need to track them |
| 221 | + readonly_props.add(rest_field._rest_name) # pylint: disable=protected-access |
| 222 | + if flattened_attribute == attr_name: |
| 223 | + for fk, fv in rest_field._class_type._attr_to_rest_field.items(): # pylint: disable=protected-access |
| 224 | + rest_to_attr[fv._rest_name] = fk # pylint: disable=protected-access |
| 225 | + else: |
| 226 | + rest_to_attr[rest_field._rest_name] = attr_name # pylint: disable=protected-access |
| 227 | + for k, v in obj.items(): |
| 228 | + if exclude_readonly and k in readonly_props: # pyright: ignore |
| 229 | + continue |
| 230 | + if k == flattened_attribute: |
| 231 | + for fk, fv in v.items(): |
| 232 | + result[rest_to_attr.get(fk, fk)] = _as_attribute_dict_value(fv, exclude_readonly=exclude_readonly) |
| 233 | + else: |
| 234 | + is_multipart_file_input = False |
| 235 | + try: |
| 236 | + is_multipart_file_input = next( # pylint: disable=protected-access |
| 237 | + rf |
| 238 | + for rf in obj._attr_to_rest_field.values() # pylint: disable=protected-access |
| 239 | + if rf._rest_name == k # pylint: disable=protected-access |
| 240 | + )._is_multipart_file_input |
| 241 | + except StopIteration: |
| 242 | + pass |
| 243 | + |
| 244 | + result[rest_to_attr.get(k, k)] = ( |
| 245 | + v if is_multipart_file_input else _as_attribute_dict_value(v, exclude_readonly=exclude_readonly) |
| 246 | + ) |
| 247 | + return result |
| 248 | + except AttributeError as exc: |
| 249 | + # not a typespec generated model |
| 250 | + raise TypeError("Object must be a generated model instance.") from exc |
0 commit comments