async_request_client.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import asyncio
  2. from typing import Optional, Dict
  3. from pprint import pformat
  4. import aiohttp
  5. from core.utils.log.logger_manager import LoggerManager
  6. class AsyncRequestClient:
  7. """
  8. 请求失败重试,本地日志记录
  9. 请求返回code!=0重试,本地日志记录
  10. 重试达到最大次数后上报阿里云日志
  11. """
  12. def __init__(self, logger:Optional[LoggerManager.get_logger()] = None ,
  13. aliyun_log:Optional[LoggerManager.get_aliyun_logger()] = None,
  14. max_retries=3, timeout=30
  15. ):
  16. self.logger = logger
  17. self.aliyun_log = aliyun_log
  18. self.max_retries = max_retries
  19. self.timeout = timeout
  20. async def request(self, session: aiohttp.ClientSession, method: str, url: str, **kwargs) -> Optional[Dict]:
  21. retries = 0
  22. while retries < self.max_retries:
  23. try:
  24. if self.logger:
  25. self.logger.info(f"请求 {method} {url}, 请求参数{kwargs}")
  26. if self.aliyun_log:
  27. self.aliyun_log.logging(
  28. code = "1012",
  29. message="初始化请求",
  30. data={"utl":url,
  31. "method":method,
  32. "requestBody":kwargs
  33. }
  34. )
  35. async with session.request(method, url, **kwargs) as response:
  36. response.raise_for_status()
  37. resp = await response.json()
  38. if resp.get('code') != 0:
  39. retries += 1
  40. if self.logger:
  41. self.logger.info(f"响应 {resp}, 重试 {retries}/{self.max_retries}")
  42. await asyncio.sleep(5)
  43. continue
  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={"utl": 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)