#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime, date from typing import Any, List, Optional from pydantic import BaseModel from sqlalchemy import asc, desc, text class ListMixin(BaseModel): data: Optional[List[Any]] = None total: Optional[int] = None errcode: int = 0 mess: str = "success" class DetailMixin(BaseModel): data: Optional[Any] = None errcode: int = 0 mess: str = "success" class Datetime2Str(date): @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v: datetime): if isinstance(v, datetime): return v.strftime("%Y-%m-%d %H:%M:%S") else: return "" class Str2Datetime(date): @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v: str): if len(v) == 10: _format_str = "%Y-%m-%d" else: _format_str = "%Y-%m-%d %H:%M:%S" try: v = datetime.strptime(v, _format_str) except Exception: raise ValueError else: return v class OrderByField(str): @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v: str): if v: fields = [x.strip() for x in v.split(",") if x.strip()] return list( map( lambda x: desc(text(x[1:])) if x.startswith("-") else asc(x), fields)) else: return [] class ReturnField(str): @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v: str): return [x.strip() for x in v.split(",") if x.strip()] class Str2List(str): @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v: str): return [x for x in v.split(";") if x.strip()]