base.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from datetime import datetime, date
  4. from typing import Any, List, Optional
  5. from pydantic import BaseModel
  6. from sqlalchemy import asc, desc, text
  7. class ListMixin(BaseModel):
  8. data: Optional[List[Any]] = None
  9. total: Optional[int] = None
  10. errcode: int = 0
  11. mess: str = "success"
  12. class DetailMixin(BaseModel):
  13. data: Optional[Any] = None
  14. errcode: int = 0
  15. mess: str = "success"
  16. class Datetime2Str(date):
  17. @classmethod
  18. def __get_validators__(cls):
  19. yield cls.validate
  20. @classmethod
  21. def validate(cls, v: datetime):
  22. if isinstance(v, datetime):
  23. return v.strftime("%Y-%m-%d %H:%M:%S")
  24. else:
  25. return ""
  26. class Str2Datetime(date):
  27. @classmethod
  28. def __get_validators__(cls):
  29. yield cls.validate
  30. @classmethod
  31. def validate(cls, v: str):
  32. if len(v) == 10:
  33. _format_str = "%Y-%m-%d"
  34. else:
  35. _format_str = "%Y-%m-%d %H:%M:%S"
  36. try:
  37. v = datetime.strptime(v, _format_str)
  38. except Exception:
  39. raise ValueError
  40. else:
  41. return v
  42. class OrderByField(str):
  43. @classmethod
  44. def __get_validators__(cls):
  45. yield cls.validate
  46. @classmethod
  47. def validate(cls, v: str):
  48. if v:
  49. fields = [x.strip() for x in v.split(",") if x.strip()]
  50. return list(
  51. map(
  52. lambda x: desc(text(x[1:]))
  53. if x.startswith("-") else asc(x), fields))
  54. else:
  55. return []
  56. class ReturnField(str):
  57. @classmethod
  58. def __get_validators__(cls):
  59. yield cls.validate
  60. @classmethod
  61. def validate(cls, v: str):
  62. return [x.strip() for x in v.split(",") if x.strip()]
  63. class Str2List(str):
  64. @classmethod
  65. def __get_validators__(cls):
  66. yield cls.validate
  67. @classmethod
  68. def validate(cls, v: str):
  69. return [x for x in v.split(";") if x.strip()]