async_request_client.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import asyncio
  2. from typing import Optional, Dict
  3. import aiohttp
  4. from core.utils.log.logger_manager import LoggerManager
  5. class AsyncRequestClient:
  6. """
  7. 请求失败重试,本地日志记录
  8. 请求返回code!=0重试,本地日志记录
  9. 重试达到最大次数后上报阿里云日志
  10. """
  11. def __init__(self, logger: Optional[LoggerManager.get_logger()] = None,
  12. aliyun_log: Optional[LoggerManager.get_aliyun_logger()] = None,
  13. max_retries=3, timeout=30):
  14. self.logger = logger
  15. self.aliyun_log = aliyun_log
  16. self.max_retries = max_retries
  17. self.timeout = timeout
  18. async def request(self, session: aiohttp.ClientSession, method: str, url: str, **kwargs) -> Optional[Dict]:
  19. retries = 0
  20. resp = None # 初始化resp变量
  21. while retries < self.max_retries:
  22. try:
  23. if self.logger:
  24. self.logger.info(f"请求 {method} {url}, 请求参数{kwargs}")
  25. if self.aliyun_log:
  26. self.aliyun_log.logging(
  27. code="1012",
  28. message="初始化请求",
  29. data={"url": url,
  30. "method": method,
  31. "requestBody": kwargs}
  32. )
  33. async with session.request(method, url, **kwargs) as response:
  34. response.raise_for_status()
  35. resp = await response.json()
  36. if resp.get('code') != 0:
  37. retries += 1
  38. if self.logger:
  39. self.logger.info(f"{url} 响应 {resp}, 重试 {retries}/{self.max_retries}")
  40. if retries >= self.max_retries:
  41. error_msg = f"请求响应code非0且达到最大重试次数 {self.max_retries}"
  42. if self.logger:
  43. self.logger.error(error_msg)
  44. if self.aliyun_log:
  45. self.aliyun_log.logging(
  46. code="9006",
  47. message=error_msg,
  48. data={
  49. "url": url,
  50. "method": method,
  51. "requestBody": kwargs,
  52. "response": resp
  53. }
  54. )
  55. await asyncio.sleep(5)
  56. continue
  57. self.logger.info(f"{url} 响应: {resp}")
  58. return resp
  59. except Exception as e:
  60. retries += 1
  61. if retries >= self.max_retries:
  62. if self.logger:
  63. self.logger.error(f"请求失败达到最大重试次数: {e}")
  64. if self.aliyun_log:
  65. self.aliyun_log.logging(
  66. code="9006",
  67. message="请求异常达到最大重试次数",
  68. data={
  69. "url": url,
  70. "method": method,
  71. "requestBody": kwargs,
  72. "response": str(resp) if resp else str(e),
  73. "error_type": type(e).__name__
  74. }
  75. )
  76. return
  77. if self.logger:
  78. self.logger.warning(f"请求失败 {e}, 重试 {retries}/{self.max_retries}")
  79. await asyncio.sleep(5)