async_request_client.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. ):
  15. self.logger = logger
  16. self.aliyun_log = aliyun_log
  17. self.max_retries = max_retries
  18. self.timeout = timeout
  19. async def request(self, session: aiohttp.ClientSession, method: str, url: str, **kwargs) -> Optional[Dict]:
  20. retries = 0
  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={"utl":url,
  30. "method":method,
  31. "requestBody":kwargs
  32. }
  33. )
  34. async with session.request(method, url, **kwargs) as response:
  35. response.raise_for_status()
  36. resp = await response.json()
  37. if resp.get('code') != 0:
  38. retries += 1
  39. if self.logger:
  40. self.logger.info(f"响应 {resp}, 重试 {retries}/{self.max_retries}")
  41. await asyncio.sleep(5)
  42. continue
  43. self.logger.info(f"响应: {resp}")
  44. return resp
  45. except Exception as e:
  46. retries += 1
  47. if retries >= self.max_retries:
  48. if self.logger:
  49. self.logger.error(f"请求失败达到最大重试次数: {e}")
  50. if self.aliyun_log:
  51. self.aliyun_log.logging(
  52. code="9006",
  53. message=f"请求异常达到最大重试次数",
  54. data={"url": url,
  55. "method": method,
  56. "requestBody": kwargs,
  57. "response": resp
  58. }
  59. )
  60. return
  61. if self.logger:
  62. self.logger.warning(f"请求失败 {e}, 重试 {retries}/{self.max_retries}")
  63. await asyncio.sleep(5)