|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +from io import BytesIO |
| 5 | +from xml.etree.ElementTree import iterparse |
| 6 | + |
| 7 | +from smithy_core.codecs import Codec |
| 8 | +from smithy_core.deserializers import ShapeDeserializer |
| 9 | +from smithy_core.interfaces import BytesReader, BytesWriter |
| 10 | +from smithy_core.serializers import ShapeSerializer |
| 11 | +from smithy_core.types import TimestampFormat |
| 12 | + |
| 13 | +from ._private.deserializers import XMLShapeDeserializer as _XMLShapeDeserializer |
| 14 | +from ._private.readers import XMLEventReader as _XMLEventReader |
| 15 | +from .settings import XMLSettings |
| 16 | + |
| 17 | +__version__ = "0.1.0" |
| 18 | +__all__ = ("XMLCodec", "XMLSettings") |
| 19 | + |
| 20 | + |
| 21 | +class XMLCodec(Codec): |
| 22 | + """A codec for converting shapes to/from XML.""" |
| 23 | + |
| 24 | + def __init__( |
| 25 | + self, |
| 26 | + use_timestamp_format: bool = True, |
| 27 | + default_timestamp_format: TimestampFormat = TimestampFormat.DATE_TIME, |
| 28 | + default_namespace: str | None = None, |
| 29 | + ) -> None: |
| 30 | + """Initializes an XMLCodec. |
| 31 | +
|
| 32 | + :param use_timestamp_format: Whether the codec should use the |
| 33 | + `smithy.api#timestampFormat` trait, if present. |
| 34 | + :param default_timestamp_format: The default timestamp format to use if the |
| 35 | + `smithy.api#timestampFormat` trait is not enabled or not present. |
| 36 | + :param default_namespace: Default XML namespace (`xmlns`) applied to the root |
| 37 | + element during serialization. |
| 38 | + """ |
| 39 | + self._settings = XMLSettings( |
| 40 | + use_timestamp_format=use_timestamp_format, |
| 41 | + default_timestamp_format=default_timestamp_format, |
| 42 | + default_namespace=default_namespace, |
| 43 | + ) |
| 44 | + |
| 45 | + @property |
| 46 | + def media_type(self) -> str: |
| 47 | + return "application/xml" |
| 48 | + |
| 49 | + def create_serializer(self, sink: BytesWriter) -> ShapeSerializer: |
| 50 | + raise NotImplementedError("XML serialization is not supported") |
| 51 | + |
| 52 | + def create_deserializer( |
| 53 | + self, |
| 54 | + source: bytes | BytesReader, |
| 55 | + *, |
| 56 | + wrapper_elements: tuple[str, ...] = (), |
| 57 | + ) -> ShapeDeserializer: |
| 58 | + if isinstance(source, bytes): |
| 59 | + source = BytesIO(source) |
| 60 | + reader = _XMLEventReader( |
| 61 | + iterparse(source, events=("start", "end")) # noqa: S314 |
| 62 | + ) |
| 63 | + return _XMLShapeDeserializer( |
| 64 | + settings=self._settings, reader=reader, wrapper_elements=wrapper_elements |
| 65 | + ) |
0 commit comments