Synchronize mcp service api
This commit is contained in:
1 parent
a0b827b32e
commit
c790fbef51
15 files changed
+316
-66
No files matched your search
@@ -0,0 +1,6 @@
|
||||
user_task_ids = [
|
||||
"configure-platform-settings",
|
||||
"add-mcp-services",
|
||||
"configure-platment-billings",
|
||||
"share-your-platform"
|
||||
]
|
||||
@@ -196,10 +196,11 @@ def get_mcp_service_list(
|
||||
"slug_name": service.slug_name,
|
||||
"short_description": service.short_description,
|
||||
"long_description": service.long_description,
|
||||
"auth_method": service.auth_method.value if service.auth_method else None,
|
||||
# "auth_method": service.auth_method.value if service.auth_method else None,
|
||||
"base_url": service.base_url,
|
||||
"auth_header": service.auth_header,
|
||||
"auth_token": service.auth_token,
|
||||
# "headers": json.loads(service.headers) if service.headers else [],
|
||||
# "auth_header": service.auth_header,
|
||||
# "auth_token": service.auth_token,
|
||||
"charge_type": service.charge_type.value if service.charge_type else None,
|
||||
"price": str(float(service.price)) if service.price and service.charge_type == ChargeType.PER_CALL else "0.00",
|
||||
"input_token_price": str(float(service.input_token_price)) if service.input_token_price and service.charge_type == ChargeType.PER_TOKEN else "0.00",
|
||||
|
||||
@@ -1,25 +1,30 @@
|
||||
from fastapi import APIRouter, Depends, Request,Body
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.database import get_db
|
||||
from services.admin_service.constants.user_task import user_task_ids
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
from services.common.response.user_response import UserResponse
|
||||
from services.common.response.user_wallet_response import UserWalletResponse
|
||||
from services.admin_service.utils.user_utils import UserUtils
|
||||
from services.admin_service.services.user_wallet_service import UserWalletService
|
||||
from services.admin_service.services.user_task_service import UserTaskService
|
||||
from services.admin_service.services.auth_service import AuthService
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
|
||||
def get_user_wallet(db: Session = Depends(get_db)) -> UserWalletService:
|
||||
return UserWalletService(db)
|
||||
|
||||
def get_auth_service(db: Session = Depends(get_db)) -> AuthService:
|
||||
return AuthService(db)
|
||||
|
||||
def get_user_task_service(db: Session = Depends(get_db)) -> UserTaskService:
|
||||
return UserTaskService(db)
|
||||
|
||||
@router.get("/info", response_model=dict)
|
||||
def get_user(request: Request, user_wallet: UserWalletService = Depends(get_user_wallet)):
|
||||
def get_user(request: Request, user_wallet: UserWalletService = Depends(get_user_wallet), user_task: UserTaskService = Depends(get_user_task_service)):
|
||||
"""Get current user information and wallet balance."""
|
||||
user_response = UserResponse()
|
||||
user_wallet_resp = UserWalletResponse()
|
||||
@@ -35,12 +40,17 @@ def get_user(request: Request, user_wallet: UserWalletService = Depends(get_user
|
||||
user_response.user_name = user.name
|
||||
user_response.user_email = user.email
|
||||
user_response.created_at = getattr(user, "created_at", None)
|
||||
user_response.wallet = user_wallet_resp
|
||||
user_response.register_type = user.register_type
|
||||
|
||||
user_response.register_type = user.register_type.value
|
||||
|
||||
user_tasks = user_task.user_tasks_by_id(user.id)
|
||||
completed_task_ids = {t.task_id for t in user_tasks if getattr(t, "task_status", 0) == 1}
|
||||
user_response.onboarding_tasks = [{"task_id": tid, "task_status": 1 if tid in completed_task_ids else 0} for tid in user_task_ids]
|
||||
|
||||
# print("register_type",user.register_type)
|
||||
# if user.register_type:
|
||||
# user_response.register_type = user.register_type.value
|
||||
|
||||
user_response.wallet = user_wallet_resp
|
||||
return ResponseUtils.success(user_response)
|
||||
return ResponseUtils.error(message="not found user", code=500)
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
from fastapi import APIRouter, Depends, Body,Request
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.database import get_db
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
from services.admin_service.services.user_task_service import UserTaskService
|
||||
from services.admin_service.utils.user_utils import UserUtils
|
||||
from services.admin_service.constants.user_task import user_task_ids
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
def get_user_task_service(db: Session = Depends(get_db)) -> UserTaskService:
|
||||
return UserTaskService(db)
|
||||
|
||||
|
||||
@router.put("/task_update_status")
|
||||
def skip_task(
|
||||
request: Request,
|
||||
body: dict = Body(...),
|
||||
user_task_service: UserTaskService = Depends(get_user_task_service),
|
||||
):
|
||||
user = UserUtils.get_request_user(request)
|
||||
if not user:
|
||||
return ResponseUtils.error(message="not found user", code=404)
|
||||
|
||||
task_id = body.get("task_id")
|
||||
if task_id:
|
||||
if task_id not in user_task_ids:
|
||||
return ResponseUtils.error(message="invalid task_id", code=400)
|
||||
raw_status = body.get("task_status", 0)
|
||||
try:
|
||||
status_int = 1 if int(raw_status) == 1 else 0
|
||||
except (ValueError, TypeError):
|
||||
status_int = 0
|
||||
user_task_service.update_task_status(user.id, task_id, status_int)
|
||||
return ResponseUtils.success()
|
||||
is_skip = body.get("is_skip")
|
||||
if is_skip and is_skip == 1:
|
||||
for task_id in user_task_ids:
|
||||
user_task_service.skip_task(user.id, task_id)
|
||||
return ResponseUtils.success()
|
||||
@@ -24,6 +24,7 @@ from services.admin_service.controllers import admin_stats
|
||||
from services.admin_service.controllers import user_stats
|
||||
from services.admin_service.controllers import email_test
|
||||
from services.admin_service.controllers import upload
|
||||
from services.admin_service.controllers import user_task
|
||||
|
||||
|
||||
|
||||
@@ -166,6 +167,9 @@ app.include_router(admin_stats.router, prefix="/api/overview")
|
||||
app.include_router(user_stats.router, prefix="/api/stats")
|
||||
app.include_router(email_test.router, prefix="/api/email_test")
|
||||
app.include_router(upload.router, prefix="/api/upload")
|
||||
app.include_router(user_task.router, prefix="/api/onboarding")
|
||||
|
||||
|
||||
|
||||
# Logging is already configured by setup_logging("admin_service")
|
||||
# 创建uploads目录(如果不存在)
|
||||
|
||||
@@ -34,10 +34,11 @@ class McpServiceRepository:
|
||||
existing_service.slug_name = mcp_service.slug_name
|
||||
existing_service.short_description = mcp_service.short_description
|
||||
existing_service.long_description = mcp_service.long_description
|
||||
existing_service.auth_method = mcp_service.auth_method
|
||||
# existing_service.auth_method = mcp_service.auth_method
|
||||
existing_service.base_url = mcp_service.base_url
|
||||
existing_service.auth_header = mcp_service.auth_header
|
||||
existing_service.auth_token = mcp_service.auth_token
|
||||
# existing_service.auth_header = mcp_service.auth_header
|
||||
# existing_service.auth_token = mcp_service.auth_token
|
||||
existing_service.headers = mcp_service.headers
|
||||
existing_service.charge_type = mcp_service.charge_type
|
||||
existing_service.price = mcp_service.price
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime, timezone
|
||||
from typing import List
|
||||
from services.common.models.user_task import UserTask
|
||||
|
||||
class UserTaskRepository:
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def user_tasks_by_id(self, user_id: str) -> List[UserTask]:
|
||||
return self.db.query(UserTask).filter(UserTask.user_id == user_id).all()
|
||||
|
||||
def skip_task(self, user_id: str, task_id: str):
|
||||
user_task = self.db.query(UserTask).filter(UserTask.user_id == user_id, UserTask.task_id == task_id).first()
|
||||
if user_task:
|
||||
user_task.task_status = 1
|
||||
user_task.updated_at = datetime.now(timezone.utc)
|
||||
else:
|
||||
user_task = UserTask(user_id=user_id, task_id=task_id, task_status=1)
|
||||
self.db.add(user_task)
|
||||
self.db.commit()
|
||||
def update_task_status(self, user_id: str, task_id: str, task_status: int):
|
||||
user_task = self.db.query(UserTask).filter(UserTask.user_id == user_id, UserTask.task_id == task_id).first()
|
||||
status_int = 1 if int(task_status) == 1 else 0
|
||||
if user_task:
|
||||
user_task.task_status = status_int
|
||||
user_task.updated_at = datetime.now(timezone.utc)
|
||||
else:
|
||||
user_task = UserTask(user_id=user_id, task_id=task_id, task_status=status_int)
|
||||
self.db.add(user_task)
|
||||
self.db.commit()
|
||||
@@ -111,10 +111,11 @@ class McpManagerService:
|
||||
existing_service.name = temp_service.name
|
||||
existing_service.short_description = temp_service.short_description
|
||||
existing_service.long_description = temp_service.long_description
|
||||
existing_service.auth_method = AuthMethod(temp_service.auth_method.value)
|
||||
existing_service.headers = temp_service.headers
|
||||
# existing_service.auth_method = AuthMethod(temp_service.auth_method.value)
|
||||
existing_service.base_url = temp_service.base_url
|
||||
existing_service.auth_header = temp_service.auth_header
|
||||
existing_service.auth_token = temp_service.auth_token
|
||||
# existing_service.auth_header = temp_service.auth_header
|
||||
# existing_service.auth_token = temp_service.auth_token
|
||||
existing_service.charge_type = ChargeType(temp_service.charge_type.value)
|
||||
existing_service.price = temp_service.price
|
||||
existing_service.input_token_price = temp_service.input_token_price
|
||||
@@ -160,29 +161,36 @@ class McpManagerService:
|
||||
existing_service.short_description = body["short_description"]
|
||||
if "long_description" in body and body["long_description"] is not None:
|
||||
existing_service.long_description = body["long_description"]
|
||||
if "auth_method" in body:
|
||||
auth_method_value = body["auth_method"]
|
||||
# If auth_method is None, empty string, or "none", default to free
|
||||
if auth_method_value is None or auth_method_value == "" or auth_method_value == "none":
|
||||
existing_service.auth_method = AuthMethod.FREE
|
||||
else:
|
||||
# Ensure the provided value is a valid AuthMethod value
|
||||
try:
|
||||
if isinstance(auth_method_value, str):
|
||||
existing_service.auth_method = AuthMethod(auth_method_value.lower())
|
||||
else:
|
||||
existing_service.auth_method = auth_method_value
|
||||
except ValueError:
|
||||
# If the provided value is not a valid AuthMethod, default to FREE
|
||||
existing_service.auth_method = AuthMethod.FREE
|
||||
if "headers" in body and body["headers"] is not None:
|
||||
if isinstance(body["headers"], str):
|
||||
existing_service.headers = body["headers"]
|
||||
elif isinstance(body["headers"], list):
|
||||
existing_service.headers = json.dumps(body["headers"])
|
||||
else:
|
||||
existing_service.auth_method = AuthMethod.FREE
|
||||
existing_service.headers = "[]"
|
||||
# if "auth_method" in body:
|
||||
# auth_method_value = body["auth_method"]
|
||||
# # If auth_method is None, empty string, or "none", default to free
|
||||
# if auth_method_value is None or auth_method_value == "" or auth_method_value == "none":
|
||||
# existing_service.auth_method = AuthMethod.FREE
|
||||
# else:
|
||||
# # Ensure the provided value is a valid AuthMethod value
|
||||
# try:
|
||||
# if isinstance(auth_method_value, str):
|
||||
# existing_service.auth_method = AuthMethod(auth_method_value.lower())
|
||||
# else:
|
||||
# existing_service.auth_method = auth_method_value
|
||||
# except ValueError:
|
||||
# # If the provided value is not a valid AuthMethod, default to FREE
|
||||
# existing_service.auth_method = AuthMethod.FREE
|
||||
# else:
|
||||
# existing_service.auth_method = AuthMethod.FREE
|
||||
if "base_url" in body and body["base_url"] is not None:
|
||||
existing_service.base_url = body["base_url"]
|
||||
if "auth_header" in body and body["auth_header"] is not None:
|
||||
existing_service.auth_header = body["auth_header"]
|
||||
if "auth_token" in body and body["auth_token"] is not None:
|
||||
existing_service.auth_token = body["auth_token"]
|
||||
# if "auth_header" in body and body["auth_header"] is not None:
|
||||
# existing_service.auth_header = body["auth_header"]
|
||||
# if "auth_token" in body and body["auth_token"] is not None:
|
||||
# existing_service.auth_token = body["auth_token"]
|
||||
if "charge_type" in body and body["charge_type"] is not None:
|
||||
charge_type_value = body["charge_type"]
|
||||
try:
|
||||
@@ -282,9 +290,10 @@ class McpManagerService:
|
||||
"short_description": service.short_description,
|
||||
"long_description": service.long_description,
|
||||
"base_url": service.base_url,
|
||||
"auth_method": service.auth_method.value if service.auth_method != AuthMethod.FREE else "none",
|
||||
"auth_header": service.auth_header,
|
||||
"auth_token": service.auth_token,
|
||||
# "auth_method": service.auth_method.value if service.auth_method != AuthMethod.FREE else "none",
|
||||
# "auth_header": service.auth_header,
|
||||
# "auth_token": service.auth_token,
|
||||
"headers":json.loads(service.headers) if service.headers else [],
|
||||
"charge_type": service.charge_type.value if service.charge_type else None,
|
||||
"price": str(float(service.price)) if service.price and service.charge_type == ChargeType.PER_CALL else "0.00",
|
||||
"input_token_price": str(float(service.input_token_price)) if service.input_token_price and service.charge_type == ChargeType.PER_TOKEN else "0.00",
|
||||
@@ -335,10 +344,11 @@ class McpManagerService:
|
||||
mcp_service.slug_name = slug_name
|
||||
mcp_service.short_description = openapi_data.description[:255] if openapi_data.description else openapi_data.title
|
||||
mcp_service.long_description = openapi_data.description
|
||||
mcp_service.auth_method = AuthMethod.FREE # Default to free
|
||||
# mcp_service.auth_method = AuthMethod.FREE # Default to free
|
||||
mcp_service.base_url = "" # Requires user configuration later
|
||||
mcp_service.auth_header = ""
|
||||
mcp_service.auth_token = ""
|
||||
# mcp_service.auth_header = ""
|
||||
# mcp_service.auth_token = ""
|
||||
mcp_service.headers = "[]"
|
||||
mcp_service.charge_type = ChargeType.FREE # Default to free
|
||||
mcp_service.price = 0.0
|
||||
mcp_service.enabled = 0 # Default disabled, requires manual activation by user
|
||||
@@ -406,10 +416,11 @@ class McpManagerService:
|
||||
temp_service.slug_name = existing_service.slug_name # Keep original slug_name
|
||||
temp_service.short_description = openapi_data.description or existing_service.short_description
|
||||
temp_service.long_description = openapi_data.description or existing_service.long_description
|
||||
temp_service.auth_method = TempAuthMethod(existing_service.auth_method.value) # Keep original auth method
|
||||
# temp_service.auth_method = TempAuthMethod(existing_service.auth_method.value) # Keep original auth method
|
||||
temp_service.base_url = existing_service.base_url # Keep original base_url
|
||||
temp_service.auth_header = existing_service.auth_header
|
||||
temp_service.auth_token = existing_service.auth_token
|
||||
# temp_service.auth_header = existing_service.auth_header
|
||||
# temp_service.auth_token = existing_service.auth_token
|
||||
temp_service.headers = existing_service.headers # Keep original headers
|
||||
temp_service.charge_type = TempChargeType(existing_service.charge_type.value) # Keep original charge type
|
||||
temp_service.price = existing_service.price # Keep original price
|
||||
temp_service.enabled = existing_service.enabled # Keep original enabled status
|
||||
@@ -457,9 +468,10 @@ class McpManagerService:
|
||||
"short_description": temp_service.short_description,
|
||||
"long_description": temp_service.long_description,
|
||||
"base_url": temp_service.base_url,
|
||||
"auth_method": temp_service.auth_method.value if temp_service.auth_method else None,
|
||||
"auth_header": temp_service.auth_header,
|
||||
"auth_token": temp_service.auth_token,
|
||||
# "auth_method": temp_service.auth_method.value if temp_service.auth_method else None,
|
||||
# "auth_header": temp_service.auth_header,
|
||||
# "auth_token": temp_service.auth_token,
|
||||
"headers": json.loads(temp_service.headers) if temp_service.headers else [],
|
||||
"charge_type": temp_service.charge_type.value if temp_service.charge_type else None,
|
||||
"price": str(float(temp_service.price)) if temp_service.price and temp_service.charge_type == ChargeType.PER_CALL else "0.00",
|
||||
"input_token_price": str(float(temp_service.input_token_price)) if temp_service.input_token_price and temp_service.charge_type == ChargeType.PER_TOKEN else "0.00",
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Optional, Tuple, List
|
||||
from services.common.models.user_task import UserTask
|
||||
from services.common.database import SessionLocal
|
||||
|
||||
from services.admin_service.repositories.user_task_repository import UserTaskRepository
|
||||
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class UserTaskService:
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
self.user_task_repo = UserTaskRepository(db)
|
||||
|
||||
def user_tasks_by_id(self, user_id: str) -> List[UserTask]:
|
||||
return self.user_task_repo.user_tasks_by_id(user_id)
|
||||
|
||||
def skip_task(self, user_id: str, task_id: str):
|
||||
return self.user_task_repo.skip_task(user_id, task_id)
|
||||
|
||||
def update_task_status(self, user_id: str, task_id: str, task_status: int):
|
||||
return self.user_task_repo.update_task_status(user_id, task_id, task_status)
|
||||
|
||||
|
||||
@@ -31,14 +31,15 @@ class McpService(Base):
|
||||
slug_name: Mapped[str] = mapped_column(String(255), unique=True, nullable=False, comment="Unique slug name for the service")
|
||||
short_description: Mapped[str] = mapped_column(String, nullable=False, comment="Short description of the service")
|
||||
long_description: Mapped[str] = mapped_column(String, nullable=True, comment="Detailed description of the service (Markdown format)")
|
||||
auth_method: Mapped[AuthMethod] = mapped_column(
|
||||
Enum(AuthMethod, values_callable=lambda obj: [e.value for e in obj]),
|
||||
nullable=False,
|
||||
comment="Authentication method: free, apikey, token",
|
||||
)
|
||||
# auth_method: Mapped[AuthMethod] = mapped_column(
|
||||
# Enum(AuthMethod, values_callable=lambda obj: [e.value for e in obj]),
|
||||
# nullable=False,
|
||||
# comment="Authentication method: free, apikey, token",
|
||||
# )
|
||||
base_url: Mapped[str] = mapped_column(String(512), nullable=True, comment="api url")
|
||||
auth_header: Mapped[str] = mapped_column(String(255), nullable=True, comment="Authentication header name")
|
||||
auth_token: Mapped[str] = mapped_column(String(255), nullable=True, comment="Authentication token value")
|
||||
# auth_header: Mapped[str] = mapped_column(String(255), nullable=True, comment="Authentication header name")
|
||||
# auth_token: Mapped[str] = mapped_column(String(255), nullable=True, comment="Authentication token value")
|
||||
headers: Mapped[str] = mapped_column(String, nullable=True, comment="Additional headers for requests (JSON Array format)")
|
||||
charge_type: Mapped[ChargeType] = mapped_column(
|
||||
Enum(ChargeType, values_callable=lambda obj: [e.value for e in obj]),
|
||||
nullable=False,
|
||||
|
||||
@@ -31,14 +31,15 @@ class TempMcpService(Base):
|
||||
slug_name: Mapped[str] = mapped_column(String(255), unique=True, nullable=False, comment="Unique slug name for the service")
|
||||
short_description: Mapped[str] = mapped_column(String, nullable=False, comment="Short description of the service")
|
||||
long_description: Mapped[str] = mapped_column(String, nullable=True, comment="Detailed description of the service (Markdown format)")
|
||||
auth_method: Mapped[AuthMethod] = mapped_column(
|
||||
Enum(AuthMethod, values_callable=lambda obj: [e.value for e in obj]),
|
||||
nullable=False,
|
||||
comment="Authentication method: free, apikey, token",
|
||||
)
|
||||
# auth_method: Mapped[AuthMethod] = mapped_column(
|
||||
# Enum(AuthMethod, values_callable=lambda obj: [e.value for e in obj]),
|
||||
# nullable=False,
|
||||
# comment="Authentication method: free, apikey, token",
|
||||
# )
|
||||
base_url: Mapped[str] = mapped_column(String(512), nullable=True, comment="api url")
|
||||
auth_header: Mapped[str] = mapped_column(String(255), nullable=True, comment="Authentication header name")
|
||||
auth_token: Mapped[str] = mapped_column(String(255), nullable=True, comment="Authentication token value")
|
||||
headers: Mapped[str] = mapped_column(String, nullable=True, comment="Additional headers for requests (JSON Array format)")
|
||||
# auth_header: Mapped[str] = mapped_column(String(255), nullable=True, comment="Authentication header name")
|
||||
# auth_token: Mapped[str] = mapped_column(String(255), nullable=True, comment="Authentication token value")
|
||||
charge_type: Mapped[ChargeType] = mapped_column(
|
||||
Enum(ChargeType, values_callable=lambda obj: [e.value for e in obj]),
|
||||
nullable=False,
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
from sqlalchemy import BigInteger, String, DateTime, Integer
|
||||
from sqlalchemy.sql import func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from services.common.models.base import Base
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class UserTask(Base):
|
||||
__tablename__ = "onboarding_task"
|
||||
|
||||
id: Mapped[int] = mapped_column(
|
||||
BigInteger,
|
||||
primary_key=True,
|
||||
autoincrement=True,
|
||||
comment="Primary key",
|
||||
)
|
||||
task_id: Mapped[str] = mapped_column(String(100), nullable=False, comment="Task ID")
|
||||
user_id: Mapped[str] = mapped_column(String(36), nullable=False, comment="User ID")
|
||||
task_status: Mapped[int] = mapped_column(
|
||||
Integer, nullable=False, comment="Task status, 0: not completed, 1: completed"
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=True,
|
||||
server_default=func.current_timestamp(),
|
||||
comment="Creation timestamp",
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=True,
|
||||
server_default=func.current_timestamp(),
|
||||
server_onupdate=func.current_timestamp(),
|
||||
comment="Last update timestamp",
|
||||
)
|
||||
@@ -12,3 +12,4 @@ class UserResponse(BaseModel):
|
||||
created_at: Optional[datetime.datetime] = None
|
||||
wallet: Optional[UserWalletResponse] = None
|
||||
register_type: Optional[str] = None
|
||||
onboarding_tasks: Optional[list] = None
|
||||
@@ -6,6 +6,7 @@ import logging
|
||||
from typing import Optional, Any
|
||||
from objtyping import to_primitive
|
||||
from services.common.redis import redis_client
|
||||
from enum import Enum as PyEnum
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -13,13 +14,41 @@ DEFAULT_CACHE_EXPIRE_TIME = 3600
|
||||
|
||||
|
||||
def get_model_cache(cache_key: str, model_class: type) -> Optional[Any]:
|
||||
"""
|
||||
"""Get cached model and reconstruct SQLAlchemy model safely.
|
||||
|
||||
Supports both legacy JSON-serialized cache values and new pickled dicts.
|
||||
Ensures Enum fields are properly restored.
|
||||
"""
|
||||
try:
|
||||
cache_value = redis_client.get(cache_key)
|
||||
if cache_value:
|
||||
return model_class(**json.loads(cache_value))
|
||||
return None
|
||||
if cache_value is None:
|
||||
return None
|
||||
|
||||
# Normalize cache value to dict
|
||||
if isinstance(cache_value, dict):
|
||||
model_data = cache_value
|
||||
elif isinstance(cache_value, str):
|
||||
try:
|
||||
model_data = json.loads(cache_value)
|
||||
except Exception:
|
||||
# Unexpected format; ignore
|
||||
logger.warning(f"Unexpected cache string format for key {cache_key}, unable to parse JSON")
|
||||
return None
|
||||
else:
|
||||
logger.warning(f"Unexpected cache type for key {cache_key}: {type(cache_value)}")
|
||||
return None
|
||||
|
||||
try:
|
||||
# Use SQLAlchemy-aware reconstruction for better type handling
|
||||
from services.common.utils.sqlalchemy_utils import SqlalchemyUtils
|
||||
return SqlalchemyUtils.dict_to_model(model_class, model_data)
|
||||
except Exception as e:
|
||||
logger.warning(f"Fallback to direct model init for key {cache_key}: {e}")
|
||||
try:
|
||||
return model_class(**model_data)
|
||||
except Exception as inner_e:
|
||||
logger.error(f"Failed to reconstruct model for key {cache_key}: {inner_e}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"Cache/DB operation failed for key {cache_key}: {e}")
|
||||
return None
|
||||
@@ -51,10 +80,36 @@ def set_cache(key: str, value: Any, expire_time: int = DEFAULT_CACHE_EXPIRE_TIME
|
||||
|
||||
|
||||
def set_model_cache(cache_key: str, model: Any, expire_time: int = DEFAULT_CACHE_EXPIRE_TIME) -> bool:
|
||||
"""
|
||||
"""Set model cache with safe serialization.
|
||||
|
||||
- For SQLAlchemy models, convert to dict via SqlalchemyUtils to avoid losing Enum fields
|
||||
- Normalize Enum values to their underlying string representation for portability
|
||||
- Store dicts via RedisClient which pickles complex types reliably
|
||||
"""
|
||||
try:
|
||||
redis_client.set(cache_key, json.dumps(to_primitive(model)), ex=expire_time)
|
||||
model_dict = None
|
||||
# Try SQLAlchemy-aware conversion first
|
||||
try:
|
||||
from services.common.utils.sqlalchemy_utils import SqlalchemyUtils
|
||||
model_dict = SqlalchemyUtils.model_to_dict(model)
|
||||
except Exception:
|
||||
# Fallback to generic primitive conversion
|
||||
try:
|
||||
model_dict = to_primitive(model)
|
||||
except Exception:
|
||||
model_dict = None
|
||||
|
||||
if not isinstance(model_dict, dict):
|
||||
logger.warning(f"set_model_cache expected dict-like model for key {cache_key}, got {type(model_dict)}")
|
||||
return False
|
||||
|
||||
# Normalize Enum values to primitive .value
|
||||
for k, v in list(model_dict.items()):
|
||||
if isinstance(v, PyEnum):
|
||||
model_dict[k] = v.value
|
||||
|
||||
# Store using RedisClient which will pickle dicts for safe retrieval
|
||||
redis_client.set(cache_key, model_dict, ex=expire_time)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to set cache for key {cache_key}: {e}")
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
from typing import get_origin, get_args
|
||||
from enum import Enum as PyEnum
|
||||
|
||||
|
||||
class SqlalchemyUtils:
|
||||
|
||||
@staticmethod
|
||||
def model_to_dict(model):
|
||||
return {column.name: getattr(model, column.name) for column in model.__table__.columns}
|
||||
result = {column.name: getattr(model, column.name) for column in model.__table__.columns}
|
||||
# Normalize Enum values to primitive for safe serialization
|
||||
for key, value in list(result.items()):
|
||||
if isinstance(value, PyEnum):
|
||||
result[key] = value.value
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def dict_to_model(model_class, data_dict):
|
||||
@@ -24,6 +33,25 @@ class SqlalchemyUtils:
|
||||
# Set attributes that exist in both the dictionary and the model
|
||||
for key, value in data_dict.items():
|
||||
if key in column_names and hasattr(instance, key):
|
||||
# Attempt to restore Enum types from strings using type annotations
|
||||
annotations = getattr(model_class, "__annotations__", {})
|
||||
ann = annotations.get(key)
|
||||
target_type = None
|
||||
if ann is not None:
|
||||
origin = get_origin(ann)
|
||||
if origin is None:
|
||||
target_type = ann
|
||||
else:
|
||||
args = get_args(ann)
|
||||
if args:
|
||||
target_type = args[0]
|
||||
|
||||
if isinstance(target_type, type) and issubclass(target_type, PyEnum) and isinstance(value, str):
|
||||
try:
|
||||
value = target_type(value)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
setattr(instance, key, value)
|
||||
|
||||
return instance
|
||||
Reference in new issue
Block a user