Skip to content

Commit

Permalink
refactor(fields): move from template to standard file
Browse files Browse the repository at this point in the history
  • Loading branch information
RobertCraigie committed Jan 26, 2024
1 parent dad7e83 commit 7e21552
Show file tree
Hide file tree
Showing 6 changed files with 32 additions and 487 deletions.
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,6 @@ src/prisma/types.py
src/prisma/enums.py
src/prisma/client.py
src/prisma/models.py
src/prisma/fields.py
src/prisma/actions.py
src/prisma/metadata.py
src/prisma/partials.py
Expand Down
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ docstring-code-format = true
"prisma.enums".msg = "This is a generated file, it should only be imported at runtime in other generated files."
"prisma.types".msg = "This is a generated file, it should only be imported at runtime in other generated files."
"prisma.client".msg = "This is a generated file, it should only be imported at runtime in other generated files."
"prisma.fields".msg = "This is a generated file, it should only be imported at runtime in other generated files."
"prisma.models".msg = "This is a generated file, it should only be imported at runtime in other generated files."
"prisma.actions".msg = "This is a generated file, it should only be imported at runtime in other generated files."
"prisma.metadata".msg = "This is a generated file, it should only be imported at runtime in other generated files."
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
{% include '_header.py.jinja' %}
{% from '_utils.py.jinja' import recursive_types with context %}
# -- template fields.py.jinja --
from typing_extensions import override
from ._compat import PYDANTIC_V2, CoreSchema, core_schema
from __future__ import annotations

import base64
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Union,
Iterator,
overload,
)
from typing_extensions import override

from pydantic import Json as _PydanticJson

from ._compat import PYDANTIC_V2, CoreSchema, core_schema

if TYPE_CHECKING:
from .types import Serializable # noqa: TID251

__all__ = (
'Json',
Expand Down Expand Up @@ -35,14 +46,14 @@
# inherit from _PydanticJson so that pydantic will automatically
# transform the json string into python objects.
class Json(BaseJson):
data: 'Serializable'
data: Serializable

def __init__(self, data: 'Serializable') -> None:
def __init__(self, data: Serializable) -> None:
self.data = data
super().__init__()

@classmethod
def keys(cls, **data: 'Serializable') -> 'Json':
def keys(cls, **data: Serializable) -> Json:
return cls(data)

if TYPE_CHECKING:
Expand All @@ -68,15 +79,15 @@ def keys(cls, **data: 'Serializable') -> 'Json':
# cast(Dict[str, Any], user.json_obj)
# prisma.validate(ExpectedType, user.json_obj) # NOTE: not implemented yet
@overload # type: ignore
def __getitem__(self, i: slice) -> List['Serializable']:
def __getitem__(self, i: slice) -> List[Serializable]:
...

@overload
def __getitem__(self, i: '_JsonKeys') -> 'Serializable':
def __getitem__(self, i: _JsonKeys) -> Serializable:
...

@override
def __getitem__(self, i: Union['_JsonKeys', slice]) -> 'Serializable': # pyright: ignore[reportIncompatibleMethodOverride]
def __getitem__(self, i: Union[_JsonKeys, slice]) -> Serializable: # pyright: ignore[reportIncompatibleMethodOverride]
...


Expand All @@ -87,12 +98,12 @@ def __init__(self, raw: bytes) -> None:
self._raw = raw

@classmethod
def encode(cls, value: bytes) -> 'Base64':
def encode(cls, value: bytes) -> Base64:
"""Encode bytes into valid Base64"""
return cls(base64.b64encode(value))

@classmethod
def fromb64(cls, value: Union[str, bytes]) -> 'Base64':
def fromb64(cls, value: Union[str, bytes]) -> Base64:
"""
Create an instance of the `Base64` class from data that has already
been encoded into a valid base 64 structure.
Expand Down Expand Up @@ -123,6 +134,7 @@ def decode_str(self, encoding: str = 'utf-8') -> str:

# Support OpenAPI schema generation
if PYDANTIC_V2:

@classmethod
def __get_pydantic_json_schema__(cls, core_schema: CoreSchema, handler: Any) -> Any:
json_schema = handler(core_schema)
Expand All @@ -131,13 +143,15 @@ def __get_pydantic_json_schema__(cls, core_schema: CoreSchema, handler: Any) ->
json_schema['format'] = 'byte'
return json_schema
else:

@classmethod
def __modify_schema__(cls, field_schema: Dict[str, object]) -> None:
field_schema['type'] = 'string'
field_schema['format'] = 'byte'

# Support converting objects into Base64 at the Pydantic level
if PYDANTIC_V2:

@classmethod
def __get_pydantic_core_schema__(
cls,
Expand All @@ -148,17 +162,16 @@ def __get_pydantic_core_schema__(
return core_schema.no_info_before_validator_function(
cls._validate,
schema=core_schema.any_schema(),
serialization=core_schema.plain_serializer_function_ser_schema(
lambda instance: str(instance)
)
serialization=core_schema.plain_serializer_function_ser_schema(lambda instance: str(instance)),
)
else:

@classmethod
def __get_validators__(cls) -> Iterator[object]:
yield cls._validate

@classmethod
def _validate(cls, value: object) -> 'Base64':
def _validate(cls, value: object) -> Base64:
if isinstance(value, Base64):
return value

Expand All @@ -169,9 +182,7 @@ def _validate(cls, value: object) -> 'Base64':
if isinstance(value, bytes):
return cls(value)

raise ValueError(
f'Could not convert type: {type(value)} to a Base64 object; Expected a string or bytes object'
)
raise ValueError(f'Could not convert type: {type(value)} to a Base64 object; Expected a string or bytes object')

@override
def __str__(self) -> str:
Expand All @@ -187,6 +198,3 @@ def __eq__(self, other: Any) -> bool:
return self._raw == other._raw

return False


from .types import Serializable
1 change: 1 addition & 0 deletions src/prisma/fields.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from ._fields import *

This file was deleted.

Loading

0 comments on commit 7e21552

Please sign in to comment.