Skip to content

Commit

Permalink
feat: added experimental init and annotation mixins
Browse files Browse the repository at this point in the history
creyD committed Jan 24, 2025

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent 2ad7700 commit eb62c87
Showing 3 changed files with 39 additions and 1 deletion.
1 change: 1 addition & 0 deletions creyPY/fastapi/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
from .base import * # noqa
from .mixins import * # noqa
4 changes: 3 additions & 1 deletion creyPY/fastapi/models/base.py
Original file line number Diff line number Diff line change
@@ -7,9 +7,11 @@
from sqlalchemy.orm import as_declarative
from sqlalchemy.sql import func

from .mixins import AutoAnnotateMixin, AutoInitMixin


@as_declarative()
class Base:
class Base(AutoAnnotateMixin, AutoInitMixin):
__abstract__ = True
# Primary key as uuid
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
35 changes: 35 additions & 0 deletions creyPY/fastapi/models/mixins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from sqlalchemy import Column


class AutoAnnotateMixin:
@classmethod
def __init_subclass__(cls) -> None:
super().__init_subclass__()
annotations = {}
for key, value in cls.__dict__.items():
if isinstance(value, Column):
annotations[key] = value.type.python_type
cls.__annotations__ = annotations


class AutoInitMixin:
@classmethod
def __init_subclass__(cls) -> None:
super().__init_subclass__()
init_params = []
for key, value in cls.__dict__.items():
if isinstance(value, Column):
if not value.nullable and not value.default and not value.server_default:
init_params.append((key, value.type.python_type))

def __init__(self, **kwargs):
super(cls, self).__init__()
for key, _ in init_params:
if key not in kwargs:
raise TypeError(f"Missing required argument: {key}")
setattr(self, key, kwargs[key])
for key, value in kwargs.items():
if key not in init_params and hasattr(self.__class__, key):
setattr(self, key, value)

cls.__init__ = __init__

0 comments on commit eb62c87

Please sign in to comment.