Skip to content

Commit

Permalink
πŸ™ Trim dict keys
Browse files Browse the repository at this point in the history
  • Loading branch information
awtkns committed Aug 12, 2024
1 parent b7e3dd0 commit fb66a08
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
14 changes: 12 additions & 2 deletions harambe/parser/parser.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Type
from typing import Any, List, Optional, Type, Union, Dict

from pydantic import BaseModel, Extra, Field, NameEmail, ValidationError, create_model

Expand Down Expand Up @@ -50,7 +50,7 @@ def validate(self, data: dict[str, Any], base_url: URL) -> dict[str, Any]:
self.model = self._schema_to_pydantic_model(self.schema)

try:
return self.model(**data).model_dump()
return self.model(**trim_dict_keys(data)).model_dump()
except ValidationError as validation_error:
raise SchemaValidationError(
data=data, schema=self.schema, message=str(validation_error)
Expand Down Expand Up @@ -156,3 +156,13 @@ def _get_type(self, field: str) -> Type[Any]:
if not field_type:
raise ValueError(f"Unsupported field type: {field}")
return field_type


# TODO: Make this a root pre validator
def trim_dict_keys(data: Union[Dict[str, Any], Any]) -> Union[Dict[str, Any], Any]:
if isinstance(data, dict):
return {key.strip(): trim_dict_keys(value) for key, value in data.items()}
elif isinstance(data, list):
return [trim_dict_keys(item) for item in data]
else:
return data
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "harambe-sdk"
version = "0.19.0"
version = "0.19.10"
description = "Data extraction SDK for Playwright πŸ’πŸŒ"
authors = ["awtkns <[email protected]>"]
readme = "README.md"
Expand Down
15 changes: 13 additions & 2 deletions test/parser/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,9 @@
(
schemas.nested_lists_and_objects_schema,
{
"departments": [
" departments": [
{
"name": "Engineering",
"name ": "Engineering",
"teams": [
{"team_name": "Backend", "members": ["Alice", "Bob"]}
],
Expand All @@ -109,6 +109,17 @@
]
},
),
(
schemas.documents_schema,
{
"documents ": [
{
" title ": "Document One",
" document_url ": "/doc1", # βœ… handles extra spaces
},
]
},
),
(
schemas.enums_schema,
{"season": "spring"},
Expand Down

0 comments on commit fb66a08

Please sign in to comment.