__init__.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """
  2. 通用api
  3. """
  4. import json
  5. from flask import jsonify
  6. SUCCESS_RESPONSE = json.dumps({
  7. "code": 1,
  8. "msg": "请求成功",
  9. "success": True,
  10. }, ensure_ascii=False)
  11. class BusinessException(Exception):
  12. """
  13. 自定义业务异常
  14. """
  15. def __init__(self, msg):
  16. super().__init__(self)
  17. self.msg = msg
  18. def raiseError(msg):
  19. """ """
  20. raise BusinessException(msg)
  21. def fail_response(msg: str):
  22. """
  23. 请求失败
  24. """
  25. return jsonify({
  26. "code": 0,
  27. "msg": msg,
  28. "success": False,
  29. })
  30. def assert_not_none(data, msg):
  31. """
  32. 断言方法
  33. """
  34. if data is None:
  35. raise BusinessException(msg)
  36. def assert_not_empty(data, msg):
  37. """
  38. 断言方法
  39. """
  40. if data is None or len(data) == 0:
  41. raise BusinessException(msg)
  42. def success(data=None):
  43. if data is None:
  44. return SUCCESS_RESPONSE
  45. return jsonify({
  46. "code": 1,
  47. "msg": "请求成功",
  48. "data": data,
  49. "success": True,
  50. })