Deserializes string to primitive type. :param data: str/int/float :param klass: str/class the class to convert to :return: int, float, str, bool, date, datetime
(data, klass, path_to_item)
| 1227 | |
| 1228 | |
| 1229 | def deserialize_primitive(data, klass, path_to_item): |
| 1230 | """Deserializes string to primitive type. |
| 1231 | |
| 1232 | :param data: str/int/float |
| 1233 | :param klass: str/class the class to convert to |
| 1234 | |
| 1235 | :return: int, float, str, bool, date, datetime |
| 1236 | """ |
| 1237 | additional_message = "" |
| 1238 | try: |
| 1239 | if klass in {datetime, date}: |
| 1240 | additional_message = ( |
| 1241 | "If you need your parameter to have a fallback " |
| 1242 | "string value, please set its type as `type: {}` in your " |
| 1243 | "spec. That allows the value to be any type. " |
| 1244 | ) |
| 1245 | if klass == datetime: |
| 1246 | if len(data) < 8: |
| 1247 | raise ValueError("This is not a datetime") |
| 1248 | # The string should be in iso8601 datetime format. |
| 1249 | parsed_datetime = parse(data) |
| 1250 | date_only = ( |
| 1251 | parsed_datetime.hour == 0 |
| 1252 | and parsed_datetime.minute == 0 |
| 1253 | and parsed_datetime.second == 0 |
| 1254 | and parsed_datetime.tzinfo is None |
| 1255 | and 8 <= len(data) <= 10 |
| 1256 | ) |
| 1257 | if date_only: |
| 1258 | raise ValueError("This is a date, not a datetime") |
| 1259 | return parsed_datetime |
| 1260 | elif klass == date: |
| 1261 | if len(data) < 8: |
| 1262 | raise ValueError("This is not a date") |
| 1263 | return parse(data).date() |
| 1264 | else: |
| 1265 | converted_value = klass(data) |
| 1266 | if isinstance(data, str) and klass == float: |
| 1267 | if str(converted_value) != data: |
| 1268 | # '7' -> 7.0 -> '7.0' != '7' |
| 1269 | raise ValueError("This is not a float") |
| 1270 | return converted_value |
| 1271 | except (OverflowError, ValueError) as ex: |
| 1272 | # parse can raise OverflowError |
| 1273 | raise ApiValueError( |
| 1274 | "{0}Failed to parse {1} as {2}".format( |
| 1275 | additional_message, repr(data), klass.__name__ |
| 1276 | ), |
| 1277 | path_to_item=path_to_item, |
| 1278 | ) from ex |
| 1279 | |
| 1280 | |
| 1281 | def get_discriminator_class(model_class, discr_name, discr_value, cls_visited): |
no test coverage detected