diff --git a/CHANGELOG.rst b/CHANGELOG.rst index a8da3bf..eab6a47 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,11 @@ Changelog ========= +0.2.2 (2022-10-07) +------------------ + +- attribute default namespace bug fixed. + 0.2.1 (2022-10-06) ------------------ diff --git a/pydantic_xml/serializers.py b/pydantic_xml/serializers.py index ce27d01..9b8316d 100644 --- a/pydantic_xml/serializers.py +++ b/pydantic_xml/serializers.py @@ -221,7 +221,7 @@ def __init__( ns = ctx.entity_ns or (ctx.parent_ns if ns_attrs else None) nsmap = ctx.parent_nsmap - self.attr_name = QName.from_alias(tag=name, ns=ns, nsmap=nsmap).uri + self.attr_name = QName.from_alias(tag=name, ns=ns, nsmap=nsmap, is_attr=True).uri def serialize( self, element: etree.Element, value: Any, *, encoder: XmlEncoder, skip_empty: bool = False, diff --git a/pydantic_xml/utils.py b/pydantic_xml/utils.py index 1c9bbc3..b40ba38 100644 --- a/pydantic_xml/utils.py +++ b/pydantic_xml/utils.py @@ -35,17 +35,23 @@ def from_uri(cls, uri: str) -> 'QName': return cls(tag=m[3], ns=m[2]) @classmethod - def from_alias(cls, tag: str, ns: Optional[str] = None, nsmap: Optional[NsMap] = None) -> 'QName': + def from_alias( + cls, tag: str, ns: Optional[str] = None, nsmap: Optional[NsMap] = None, is_attr: bool = False, + ) -> 'QName': """ Creates `QName` from namespace alias. :param tag: entity tag :param ns: xml namespace alias :param nsmap: xml namespace mapping + :param is_attr: is the tag of attribute type :return: qualified name """ - return QName(tag=tag, ns=nsmap.get(ns or '') if nsmap else None) + if not is_attr or ns is not None: + ns = nsmap.get(ns or '') if nsmap else None + + return QName(tag=tag, ns=ns) @property def uri(self) -> str: diff --git a/pyproject.toml b/pyproject.toml index d784b18..f95e20c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "pydantic-xml" -version = "0.2.1" +version = "0.2.2" description = "pydantic xml serialization/deserialization extension" authors = ["Dmitry Pershin "] license = "Unlicense" diff --git a/tests/test_namespaces.py b/tests/test_namespaces.py index ae36be6..b444666 100644 --- a/tests/test_namespaces.py +++ b/tests/test_namespaces.py @@ -7,7 +7,9 @@ def test_default_namespaces(): - class TestSubMode2(BaseXmlModel): + class TestSubMode2(BaseXmlModel, nsmap={'tst': 'http://test3.org'}): + attr1: int = attr() + attr2: int = attr(ns='tst') element: str = element() class TestSubModel1(BaseXmlModel): @@ -19,7 +21,7 @@ class TestModel(BaseXmlModel, tag='model'): xml = ''' - + value @@ -28,7 +30,7 @@ class TestModel(BaseXmlModel, tag='model'): actual_obj = TestModel.from_xml(xml) expected_obj = TestModel( - submodel1=TestSubModel1(submodel2=TestSubMode2(element='value')), + submodel1=TestSubModel1(submodel2=TestSubMode2(element='value', attr1=1, attr2=2)), ) assert actual_obj == expected_obj