response_util.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. from typing import Any, Optional
  2. from fastapi import status
  3. from fastapi.encoders import jsonable_encoder
  4. from fastapi.responses import JSONResponse, Response, StreamingResponse
  5. from core.constant import HttpStatusConstant
  6. class ResponseUtil:
  7. """
  8. 响应工具类
  9. """
  10. @classmethod
  11. def response(
  12. cls,
  13. success: bool = True,
  14. code: int = HttpStatusConstant.SUCCESS,
  15. msg: str = "操作成功",
  16. data: Optional[Any] = None,
  17. ):
  18. result = {
  19. "success": success,
  20. "code": code,
  21. "message": msg,
  22. "data": data,
  23. }
  24. return JSONResponse(
  25. status_code=status.HTTP_200_OK, content=jsonable_encoder(result)
  26. )
  27. @classmethod
  28. def success(cls, data: Optional[Any] = None, msg: str = None) -> Response:
  29. return cls.response(msg=msg if msg else "操作成功", data=data)
  30. @classmethod
  31. def failure(
  32. cls,
  33. msg: str = None,
  34. data: Optional[Any] = None,
  35. code: int = HttpStatusConstant.WARN,
  36. ) -> Response:
  37. return cls.response(False, code, msg if msg else "操作失败", data)
  38. @classmethod
  39. def unauthorized(
  40. cls,
  41. msg: str = None,
  42. data: Optional[Any] = None,
  43. ) -> Response:
  44. return cls.failure(
  45. msg if msg else "登录信息已过期,访问系统资源失败",
  46. data,
  47. HttpStatusConstant.UNAUTHORIZED,
  48. )
  49. @classmethod
  50. def forbidden(
  51. cls,
  52. msg: str = None,
  53. data: Optional[Any] = None,
  54. ) -> Response:
  55. return cls.failure(
  56. msg if msg else "没有权限,访问系统资源失败",
  57. data,
  58. HttpStatusConstant.FORBIDDEN,
  59. )
  60. @classmethod
  61. def error(
  62. cls,
  63. msg: str = None,
  64. data: Optional[Any] = None,
  65. ) -> Response:
  66. return cls.failure(
  67. msg if msg else "系统服务异常", data, HttpStatusConstant.ERROR
  68. )
  69. @classmethod
  70. def not_found(cls, path: Optional[str] = None) -> Response:
  71. return cls.failure(
  72. f"[{path}]资源不存在" if path else "资源不存在",
  73. code=HttpStatusConstant.NOT_FOUND,
  74. )
  75. @classmethod
  76. def streaming(cls, *, data: Any = None):
  77. """
  78. 流式响应方法
  79. :param data: 流式传输的内容
  80. :return: 流式响应结果
  81. """
  82. return StreamingResponse(status_code=status.HTTP_200_OK, content=data)
  83. @classmethod
  84. def json(cls, data: Any = None):
  85. """
  86. JSON响应方法
  87. :param data: JSON响应的内容
  88. :return: JSON响应结果
  89. """
  90. return JSONResponse(status_code=status.HTTP_200_OK, content=data)