Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Respect custom fields style #38

Merged
merged 2 commits into from
Apr 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 26 additions & 10 deletions yatracker/tracker/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,14 @@ def _prepare_payload(
"""Remove empty fields from payload."""
payload = payload.copy()
exclude = exclude or []
kwargs = payload.pop("kwargs", None)

kwargs: dict | None = payload.pop("kwargs", None)
if kwargs:
if type_ is not None:
kwargs = _replace_custom_fields(kwargs, type_)
payload.update(kwargs)

if type_ is not None:
return _rename_and_clear(type_, payload, exclude)

return {
camel_case(k): _convert_value(v)
for k, v in payload.items()
Expand Down Expand Up @@ -144,12 +145,27 @@ def _convert_value(obj: Any) -> Any: # noqa: ANN401
return obj


def _replace_custom_fields(kwargs: dict[str, Any], type_: type[B]) -> dict[str, Any]:
def _rename_and_clear(
type_: type[B],
payload: dict[str, Any],
exclude: Collection[str],
) -> dict[str, Any]:
"""Replace kwarg key with original field name."""
new_kwargs: dict[str, Any] = {}
for key, value in kwargs.items():
if not hasattr(type_, key):
renamed: dict[str, Any] = {}
exclude = {"self", "cls", *exclude}

for name, encode_name in zip(
type_.__struct_fields__,
type_.__struct_encode_fields__, # type: ignore[attr-defined]
strict=False,
):
if name not in payload or name in exclude or name.startswith("_"):
continue

value = _convert_value(payload[name])
if value is None:
continue
field = getattr(type_, key)
new_kwargs[field.name] = value
return new_kwargs

renamed[encode_name] = value

return renamed
Loading