mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
b718e8e626
* Add GetterDict example * Update docs/usage/models.md Co-authored-by: Samuel Colvin <samcolvin@gmail.com> Co-authored-by: Samuel Colvin <samcolvin@gmail.com>
44 lines
902 B
Python
44 lines
902 B
Python
from pydantic import BaseModel
|
|
from typing import Any, Optional
|
|
from pydantic.utils import GetterDict
|
|
from xml.etree.ElementTree import fromstring
|
|
|
|
|
|
xmlstring = """
|
|
<User Id="2138">
|
|
<FirstName />
|
|
<LoggedIn Value="true" />
|
|
</User>
|
|
"""
|
|
|
|
|
|
class UserGetter(GetterDict):
|
|
|
|
def get(self, key: str, default: Any) -> Any:
|
|
|
|
# element attributes
|
|
if key in {'Id', 'Status'}:
|
|
return self._obj.attrib.get(key, default)
|
|
|
|
# element children
|
|
else:
|
|
try:
|
|
return self._obj.find(key).attrib['Value']
|
|
except (AttributeError, KeyError):
|
|
return default
|
|
|
|
|
|
class User(BaseModel):
|
|
Id: int
|
|
Status: Optional[str]
|
|
FirstName: Optional[str]
|
|
LastName: Optional[str]
|
|
LoggedIn: bool
|
|
|
|
class Config:
|
|
orm_mode = True
|
|
getter_dict = UserGetter
|
|
|
|
|
|
user = User.from_orm(fromstring(xmlstring))
|