From ee5147cfd7de2add74a285537a8968ec074e70cd Mon Sep 17 00:00:00 2001 From: Amir Karimi Date: Thu, 12 Sep 2024 10:56:18 +0200 Subject: Fixed #29522 -- Refactored the Deserializer functions to classes. Co-authored-by: Emad Mokhtar --- django/core/serializers/pyyaml.py | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) (limited to 'django/core/serializers/pyyaml.py') diff --git a/django/core/serializers/pyyaml.py b/django/core/serializers/pyyaml.py index 9a20b6658f..ed6e4b3895 100644 --- a/django/core/serializers/pyyaml.py +++ b/django/core/serializers/pyyaml.py @@ -6,7 +6,6 @@ Requires PyYaml (https://pyyaml.org/), but that's checked for in __init__. import collections import decimal -from io import StringIO import yaml @@ -66,17 +65,23 @@ class Serializer(PythonSerializer): return super(PythonSerializer, self).getvalue() -def Deserializer(stream_or_string, **options): +class Deserializer(PythonDeserializer): """Deserialize a stream or string of YAML data.""" - if isinstance(stream_or_string, bytes): - stream_or_string = stream_or_string.decode() - if isinstance(stream_or_string, str): - stream = StringIO(stream_or_string) - else: + + def __init__(self, stream_or_string, **options): stream = stream_or_string - try: - yield from PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options) - except (GeneratorExit, DeserializationError): - raise - except Exception as exc: - raise DeserializationError() from exc + if isinstance(stream_or_string, bytes): + stream = stream_or_string.decode() + try: + objects = yaml.load(stream, Loader=SafeLoader) + except Exception as exc: + raise DeserializationError() from exc + super().__init__(objects, **options) + + def _handle_object(self, obj): + try: + yield from super()._handle_object(obj) + except (GeneratorExit, DeserializationError): + raise + except Exception as exc: + raise DeserializationError(f"Error deserializing object: {exc}") from exc -- cgit v1.3