refactoring

This commit is contained in:
Alexander Kalinovsky
2025-01-09 13:11:10 +01:00
parent 7793a0cb77
commit 3898a333fa
29 changed files with 1065 additions and 381 deletions

View File

@@ -3,7 +3,7 @@ from decimal import Decimal
from types import NoneType, UnionType
from sqlmodel import select, column
from sqlmodel.ext.asyncio.session import AsyncSession
from typing import Any, get_origin, get_args, TYPE_CHECKING
from typing import Any, Union, get_origin, get_args, TYPE_CHECKING
import ujson as json
from ..model.bot_entity import BotEntity
@@ -18,7 +18,7 @@ if TYPE_CHECKING:
async def deserialize[T](session: AsyncSession, type_: type[T], value: str = None) -> T:
type_origin = get_origin(type_)
is_optional = False
if type_origin == UnionType:
if type_origin in [UnionType, Union]:
args = get_args(type_)
if args[1] == NoneType:
type_ = args[0]
@@ -45,6 +45,8 @@ async def deserialize[T](session: AsyncSession, type_: type[T], value: str = Non
else:
return values
elif issubclass(type_, BotEntity):
if is_optional and not value:
return None
return await session.get(type_, int(value))
elif issubclass(type_, BotEnum):
if is_optional and not value:
@@ -70,23 +72,15 @@ def serialize(value: Any, field_descriptor: EntityFieldDescriptor) -> str:
if value is None:
return ""
type_ = field_descriptor.type_
type_origin = get_origin(type_)
if type_origin == UnionType:
args = get_args(type_)
if args[1] == NoneType:
type_ = get_args(type_)[0]
if type_origin == list:
arg_type = None
args = get_args(type_)
if args:
arg_type = args[0]
if arg_type and issubclass(arg_type, BotEntity):
return json.dumps([item.id for item in value])
elif arg_type and issubclass(arg_type, BotEnum):
return json.dumps([item.value for item in value])
type_ = field_descriptor.type_base
if field_descriptor.is_list:
if issubclass(type_, BotEntity):
return json.dumps([item.id for item in value], ensure_ascii = False)
elif issubclass(type_, BotEnum):
return json.dumps([item.value for item in value], ensure_ascii = False)
else:
return json.dumps(value)
return json.dumps(value, ensure_ascii = False)
elif issubclass(type_, BotEntity):
return str(value.id) if value else ""
return str(value)
@@ -100,4 +94,13 @@ def get_user_permissions(user: "UserBase", entity_descriptor: EntityDescriptor)
if role in user.roles:
permissions.append(permission)
break
return permissions
return permissions
def get_local_text(text: str, locale: str) -> str:
try:
obj = json.loads(text) #@IgnoreException
except:
return text
else:
return obj.get(locale, obj[list(obj.keys())[0]])