Skip to content

Commit

Permalink
refactor: ajust typing, exceptions classes, get_pydantic_version, add…
Browse files Browse the repository at this point in the history
… __version__
  • Loading branch information
scjorge committed Jul 30, 2024
1 parent 2e3d57b commit 64f83f8
Show file tree
Hide file tree
Showing 9 changed files with 1,612 additions and 1,551 deletions.
2,883 changes: 1,471 additions & 1,412 deletions poetry.lock

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion pydantic_br/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from typing import TYPE_CHECKING

from .field_erros import *
from .field_errors import *

__version__ = "1.0.0"

if TYPE_CHECKING:
CPF = str
Expand Down
36 changes: 0 additions & 36 deletions pydantic_br/field_class_errors.py

This file was deleted.

74 changes: 74 additions & 0 deletions pydantic_br/field_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
from enum import Enum

from .get_versions import get_pydantic_version

__all__ = [
"FieldTypeError",
"FieldMaskError",
"FieldDigitError",
"FieldInvalidError",
"raise_field",
]


pydantic_version = get_pydantic_version()


class FieldTypes(Enum):
type = "type"
mask = "mask"
digit = "digit"
invalid = "invalid"


class FieldTypeError:
code = "not_str"
msg_template = "Input should be a valid string"
message_template = msg_template


class FieldMaskError:
code = "invalid_mask"
msg_template = "invalid mask format"
message_template = msg_template


class FieldDigitError:
code = "not_digits"
msg_template = "field only accept digits as string"
message_template = msg_template


class FieldInvalidError:
code = "invalid_data"
msg_template = "invalid data"
message_template = msg_template


def raise_error(code: str, msg_template: str): # type: ignore
if pydantic_version.value == 1:
from pydantic import PydanticTypeError

PydanticTypeError.code = code
PydanticTypeError.msg_template = msg_template
PydanticTypeError.message_template = msg_template
raise PydanticTypeError()

if pydantic_version.value == 2:
from pydantic_core import PydanticCustomError

PydanticCustomError.code = code
PydanticCustomError.msg_template = msg_template
PydanticCustomError.message_template = msg_template
raise PydanticCustomError(code, msg_template)


def raise_field(context: FieldTypes):
field_types = {
FieldTypes.type: (FieldTypeError.code, FieldTypeError.msg_template),
FieldTypes.mask: (FieldMaskError.code, FieldMaskError.msg_template),
FieldTypes.digit: (FieldDigitError.code, FieldDigitError.msg_template),
FieldTypes.invalid: (FieldInvalidError.code, FieldInvalidError.msg_template),
}

raise_error(*field_types.get(context))
35 changes: 0 additions & 35 deletions pydantic_br/field_erros.py

This file was deleted.

35 changes: 6 additions & 29 deletions pydantic_br/fields/base_field.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
from typing import Any, Callable, Dict, Generator

from ..field_erros import (
FieldDigitError,
FieldInvalidError,
FieldMaskError,
FieldTypeError,
)
from ..get_versions import get_pydantic_version
from ..field_errors import FieldTypes, raise_field
from ..validators.base_validator import FieldMaskValidator, FieldValidator
from .base_field_v2 import BaseDigitsV2, BaseMaskV2, BasePydanticV2

Expand All @@ -19,18 +13,13 @@
AnyCallable = Callable[..., Any]
CallableGenerator = Generator[AnyCallable, None, None]

pydantic_version = get_pydantic_version()


class Base(BasePydanticV2):
format: str
Validator: Callable[..., FieldValidator]

__slots__ = ["number"]

def __init__(self, number: str) -> None:
self.number = number

@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
field_schema.update(type="string", format=cls.format)
Expand All @@ -41,22 +30,16 @@ def __get_validators__(cls) -> CallableGenerator:
yield cls.validate

@classmethod
def validate_type(cls, value: str) -> str:
def validate_type(cls, value: Any) -> str:
if not isinstance(value, str):
if pydantic_version.value == 1:
raise FieldTypeError()
if pydantic_version.value == 2:
raise FieldTypeError(FieldTypeError.msg_template)
raise_field(FieldTypes.type)
return value

@classmethod
def validate(cls, value: str) -> str:
doc = cls.Validator(value)
if not doc.validate():
if pydantic_version.value == 1:
raise FieldInvalidError()
if pydantic_version.value == 2:
raise FieldInvalidError(FieldInvalidError.msg_template)
raise_field(FieldTypes.invalid)
return value


Expand All @@ -73,10 +56,7 @@ def __get_validators__(cls) -> CallableGenerator:
def validate_mask(cls, value: str) -> str:
doc = cls.Validator(value)
if not doc.validate_mask():
if pydantic_version.value == 1:
raise FieldMaskError()
if pydantic_version.value == 2:
raise FieldMaskError(FieldMaskError.msg_template)
raise_field(FieldTypes.mask)
return value


Expand All @@ -90,8 +70,5 @@ def __get_validators__(cls) -> CallableGenerator:
@classmethod
def validate_numbers(cls, value: str) -> str:
if not value.isdigit():
if pydantic_version.value == 1:
raise FieldDigitError()
if pydantic_version.value == 2:
raise FieldDigitError(FieldDigitError.msg_template)
raise_field(FieldTypes.digit)
return value
69 changes: 44 additions & 25 deletions pydantic_br/fields/base_field_v2.py
Original file line number Diff line number Diff line change
@@ -1,68 +1,87 @@
from typing import Any, Dict
from __future__ import annotations

from typing import Any, Dict, Mapping, TypeAlias

from ..get_versions import get_pydantic_version

pydantic_version = get_pydantic_version()


if pydantic_version.value == 1:

class core_schema: # noqa
def CoreSchema(self):
...

def general_after_validator_function(self):
...
if pydantic_version.value == 2:
try:
from pydantic_core import core_schema # type: ignore
except ModuleNotFoundError:
raise ModuleNotFoundError("Are you sure you installed pydantic_core")

def str_schema(self):
...
CoreSchema: TypeAlias = Mapping[str, Any]
JsonSchemaValue = Dict[str, Any]

def ValidationInfo(self):
...

class BasePydanticV2:
format = "generic"

if pydantic_version.value == 2:
from pydantic_core import core_schema # noqa
@classmethod
def validate_type(cls, value: Any):
...

@classmethod
def validate(cls, value: str):
...

JsonSchemaValue = Dict[str, Any]
@classmethod
def validate_mask(cls, value: str):
...

@classmethod
def validate_numbers(cls, value: str):
...

class BasePydanticV2:
@classmethod
def __get_pydantic_core_schema__(
cls,
source,
) -> core_schema.CoreSchema:
return core_schema.general_after_validator_function(
cls._validate, core_schema.str_schema()
)
*args,
**kwargs,
) -> CoreSchema:
try:
schema = core_schema.with_info_after_validator_function(
cls._validate, core_schema.str_schema()
)
except Exception:
schema = core_schema.general_after_validator_function(
cls._validate, core_schema.str_schema()
)
return schema

@classmethod
def __get_pydantic_json_schema__(
cls, core_schema: core_schema.CoreSchema, handler
cls,
core_schema: CoreSchema,
handler,
*args,
**kwargs,
) -> JsonSchemaValue:
field_schema = handler(core_schema)
field_schema.update(type="string", format=cls.format)
return field_schema

@classmethod
def _validate(cls, __input_value: str, _: core_schema.ValidationInfo) -> str:
def _validate(cls, __input_value: str, *args, **kwargs) -> str:
cls.validate_type(__input_value)
return cls.validate(__input_value)


class BaseMaskV2(BasePydanticV2):
@classmethod
def _validate(cls, __input_value: str, _: core_schema.ValidationInfo) -> str:
def _validate(cls, __input_value: str, *args, **kwargs) -> str:
cls.validate_type(__input_value)
cls.validate_mask(__input_value)
return cls.validate(__input_value)


class BaseDigitsV2(BasePydanticV2):
@classmethod
def _validate(cls, __input_value: str, _: core_schema.ValidationInfo) -> str:
def _validate(cls, __input_value: str, *args, **kwargs) -> str:
cls.validate_type(__input_value)
cls.validate_numbers(__input_value)
return cls.validate(__input_value)
11 changes: 6 additions & 5 deletions pydantic_br/get_versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ def get_pydantic_version() -> PydanticVersion:
except ModuleNotFoundError:
raise ModuleNotFoundError("Are you sure you installed Pydantic")

if pydantic.__version__.startswith("1"):
return PydanticVersion.v1
if pydantic.__version__.startswith("2"):
return PydanticVersion.v2
raise ModuleNotFoundError("Something went wrong withs Pydantic imports")
if hasattr(pydantic, "__version__"):
if pydantic.__version__.startswith("1"):
return PydanticVersion.v1
if pydantic.__version__.startswith("2"):
return PydanticVersion.v2
return PydanticVersion.v1
Loading

0 comments on commit 64f83f8

Please sign in to comment.