Created
December 13, 2020 13:00
-
-
Save MattOates/7f8364f8da07c36874c0e9c2443dab19 to your computer and use it in GitHub Desktop.
Attempt to make a nice Tortoise BaseModel to work with FastAPI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import ( | |
Type, | |
Optional, | |
) | |
from tortoise.models import Model | |
from tortoise.contrib.pydantic import ( | |
pydantic_model_creator, | |
PydanticModel, | |
) | |
class pydantic: | |
def __init__(self, *args, **kwargs): | |
self.args = args | |
self.kwargs = kwargs | |
self.pydantic_model = None | |
def __set_name__(self, owner, name): | |
self.owner = owner | |
self.name = name | |
def __get__(self, instance: Optional[Model], typevar: Type[Model]) -> Type[PydanticModel]: | |
if instance is None: | |
if self.pydantic_model is None: | |
self.pydantic_model = pydantic_model_creator( | |
self.owner.__class__, | |
*self.args, | |
name=self.owner.__name__ + self.name.title(), | |
**self.kwargs | |
) | |
return self.pydantic_model | |
return self.pydantic_model | |
class BaseModel(Model): | |
All = pydantic() | |
Write = pydantic(exclude_readonly=True) | |
async def pydantic(self): | |
# TODO: get a type constraing on this | |
return await self.All.from_tortoise_orm(self) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment