Skip to content

Commit

Permalink
Translation POC
Browse files Browse the repository at this point in the history
  • Loading branch information
acidjunk authored and Rene Dohmen committed Oct 19, 2024
1 parent 0fd33d8 commit d387f2a
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 7 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ source venv/bin/activate
pip install flit
```

### Step 2 - symlink the core to your own project
### Step 2 - symlink pydantic-forms to your own project

```shell
flit install --deps develop --symlink --python /path/to/a/project/venv/bin/python
Expand Down
28 changes: 25 additions & 3 deletions pydantic_forms/core/asynchronous.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,21 @@
# limitations under the License.
from copy import deepcopy
from inspect import isasyncgenfunction
from typing import Any, Union
from typing import Any, Union, cast

import structlog
from pydantic import ValidationError
from pydantic_forms.core.translations import tr


from pydantic_forms.core.shared import FORMS
from pydantic_forms.exceptions import FormException, FormNotCompleteError, FormOverflowError, FormValidationError
from pydantic_forms.exceptions import (
ErrorDict,
FormException,
FormNotCompleteError,
FormOverflowError,
FormValidationError,
)
from pydantic_forms.types import InputForm, State, StateInputFormGeneratorAsync

logger = structlog.get_logger(__name__)
Expand Down Expand Up @@ -67,7 +75,21 @@ async def post_form(
try:
form_validated_data = generated_form(**user_input)
except ValidationError as e:
raise FormValidationError(generated_form.__name__, e) from e # type: ignore
print("TYPE ERROR")
print(type(e.errors()[0]))
print(e.errors()[0])
print("TYPE TRANS")
translated_errors = tr.translate(e.errors(), locale="nl_NL")
print(type(translated_errors[0]))
print(translated_errors[0])
e.errors = translated_errors
# for error in translated_errors:
# print(ErrorDetails(**error))

# detail = ErrorDetails()
# detail.errors = translated_errors
# print(ErrorDetails = translated_errors)
raise FormValidationError(generated_form.__name__, translated_errors) from e # type: ignore

# Update state with validated_data
current_state.update(form_validated_data.model_dump())
Expand Down
18 changes: 18 additions & 0 deletions pydantic_forms/core/translations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from pydantic_i18n import PydanticI18n

translations = {
"en_US": {
"Field required": "field required",
},
"de_DE": {
"Field required": "Feld erforderlich",
"Value should have at least 1 item after validation, not 0": "Der Wert sollte nach der Validierung mindestens 1 Element haben, nicht 0",
},
"nl_NL": {
"Field required": "Veld verplicht",
"Value should have at least 1 item after validation, not 0": "De waarde moet na validatie minimaal 1 item bevatten, niet 0",
},
}


tr = PydanticI18n(translations)
9 changes: 7 additions & 2 deletions pydantic_forms/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from pydantic import ValidationError
from pydantic_core import ErrorDetails

from pydantic_forms.core.translations import tr

from pydantic_forms.types import JSON


Expand All @@ -31,7 +33,8 @@ class FormOverflowError(FormException):
"""Raised when more inputs are provided than the form can process."""


def convert_errors(validation_error: ValidationError) -> Iterable[ErrorDetails]:
# def convert_errors(validation_error: ValidationError) -> Iterable[ErrorDetails]:
def convert_errors(validation_error: list[dict]) -> Iterable[ErrorDetails]:
"""Convert Pydantic's error messages to our needs.
https://docs.pydantic.dev/2.4/errors/errors/#customize-error-messages
Expand All @@ -48,7 +51,7 @@ def convert_error(error: ErrorDetails) -> None:
error["loc"] = ("__root__",)
return

return side_effect(convert_error, validation_error.errors())
return side_effect(convert_error, validation_error)


class FormValidationError(FormException):
Expand All @@ -58,6 +61,8 @@ class FormValidationError(FormException):
def __init__(self, validator_name: str, error: ValidationError):
super().__init__()
self.validator_name = validator_name
print("TYPE BEFORE CON")
print(type(error[0]))
self.errors = list(convert_errors(error))

def __str__(self) -> str:
Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ classifiers = [
]
requires = [
"more-itertools",
"pydantic[email]>=2.7.4"
"pydantic[email]>=2.7.4",
"pydantic-i18n==0.4.5"
]
description-file = "README.md"
requires-python = ">=3.9,<=3.13"
Expand Down

0 comments on commit d387f2a

Please sign in to comment.