добавлен конвертер + базовый класс

This commit is contained in:
sergey 2024-07-11 21:26:30 +03:00
parent 88f6524ef6
commit 6cf72d26b5
5 changed files with 52 additions and 1 deletions

View File

@ -1,5 +1,7 @@
__all__ = ( __all__ = (
'db_helper' 'db_helper',
'Base'
) )
from .db_helper import db_helper from .db_helper import db_helper
from .base import Base

View File

@ -0,0 +1,14 @@
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, declared_attr
from utils import camel_case_to_snake_case
class Base(DeclarativeBase):
__abstract__ = True
@declared_attr.directive
def __tablename__(cls) -> str:
return f'{camel_case_to_snake_case(cls.__name__)}s'
id: Mapped[int] = mapped_column(primary_key=True)

View File

@ -16,6 +16,7 @@ async def lifespan(app: FastAPI):
main_app = FastAPI( main_app = FastAPI(
lifespan=lifespan, lifespan=lifespan,
) )
main_app.include_router(api_router, main_app.include_router(api_router,
prefix=settings.api.prefix) prefix=settings.api.prefix)

View File

@ -0,0 +1,5 @@
__all__ = (
'camel_case_to_snake_case',
)
from .case_converter import camel_case_to_snake_case

View File

@ -0,0 +1,29 @@
"""
Taken from
https://github.com/mahenzon/ri-sdk-python-wrapper/blob/master/ri_sdk_codegen/utils/case_converter.py
"""
def camel_case_to_snake_case(input_str: str) -> str:
"""
>>> camel_case_to_snake_case("SomeSDK")
'some_sdk'
>>> camel_case_to_snake_case("RServoDrive")
'r_servo_drive'
>>> camel_case_to_snake_case("SDKDemo")
'sdk_demo'
"""
chars = []
for c_idx, char in enumerate(input_str):
if c_idx and char.isupper():
nxt_idx = c_idx + 1
# idea of the flag is to separate abbreviations
# as new words, show them in lower case
flag = nxt_idx >= len(input_str) or input_str[nxt_idx].isupper()
prev_char = input_str[c_idx - 1]
if prev_char.isupper() and flag:
pass
else:
chars.append("_")
chars.append(char.lower())
return "".join(chars)