Coverage for fss\common\result\result.py: 85%

34 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2024-04-12 22:20 +0800

1"""The results returned by the project""" 

2 

3from typing import Sequence 

4from math import ceil 

5from typing import Generic, TypeVar, Any, Optional 

6 

7from fastapi_pagination import Params, Page 

8from fastapi_pagination.bases import AbstractPage, AbstractParams 

9from pydantic import Field, BaseModel 

10 

11DataType = TypeVar("DataType") 

12T = TypeVar("T") 

13 

14DEFAULT_SUCCESS_CODE: int = 0 

15DEFAULT_SUCCESS_MSG: str = "success" 

16 

17 

18class BaseResponse(BaseModel, Generic[T]): 

19 msg: str = "" 

20 code: Optional[int] = DEFAULT_SUCCESS_CODE 

21 data: Optional[T] = None 

22 

23 

24class PageBase(Page[T], Generic[T]): 

25 previous_page: Optional[int] = Field( 

26 default=None, description="Page number of the previous page" 

27 ) 

28 next_page: Optional[int] = Field( 

29 default=None, description="Page number of the next page" 

30 ) 

31 

32 

33class IPage(AbstractPage[T], Generic[T]): 

34 msg: Optional[str] = "" 

35 code: Optional[int] = DEFAULT_SUCCESS_CODE 

36 data: PageBase[T] 

37 

38 __params_type__ = Params 

39 

40 @classmethod 

41 def create( 

42 cls, 

43 items: Sequence[T], 

44 total: int, 

45 params: AbstractParams, 

46 ) -> Optional[PageBase[T]]: 

47 if params.size is not None and total is not None and params.size != 0: 

48 pages = ceil(total / params.size) 

49 else: 

50 pages = 0 

51 

52 return cls( 

53 data=PageBase[T]( 

54 items=items, 

55 page=params.page, 

56 size=params.size, 

57 total=total, 

58 pages=pages, 

59 next_page=params.page + 1 if params.page < pages else None, 

60 previous_page=params.page - 1 if params.page > 1 else None, 

61 ) 

62 ) 

63 

64 

65def success( 

66 data: DataType = None, 

67 msg: Optional[str] = "success", 

68 code: Optional[int] = DEFAULT_SUCCESS_CODE, 

69) -> Any: 

70 if data is None: 

71 return {"code": code, "msg": msg} 

72 return {"code": code, "msg": msg, "data": data} 

73 

74 

75def fail(msg: str, code: int) -> Any: 

76 return {"code": code, "msg": msg}