mirror of
https://github.com/creyD/creyPY.git
synced 2026-04-12 19:30:30 +02:00
feat: added experimental init and annotation mixins
This commit is contained in:
@@ -1 +1,2 @@
|
||||
from .base import * # noqa
|
||||
from .mixins import * # noqa
|
||||
|
||||
@@ -7,9 +7,11 @@ from sqlalchemy.ext.declarative import declared_attr
|
||||
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
creyPY/fastapi/models/mixins.py
Normal file
35
creyPY/fastapi/models/mixins.py
Normal file
@@ -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__
|
||||
Reference in New Issue
Block a user