utils.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import json
  2. import requests
  3. from common.error import NoValidError
  4. from common.logger import logger
  5. from common import config
  6. from util.login import LoginApi
  7. cookies = {}
  8. def call_api(endpoint, method="GET", params=None, data=None) -> dict:
  9. """
  10. 通用的API调用方法。
  11. """
  12. # 记录调用的信息
  13. global cookies
  14. url = f"{config.BASE_URL}{endpoint}"
  15. for i in range(3):
  16. try:
  17. if method.upper() == "GET":
  18. response = requests.get(url, params=params, cookies=cookies)
  19. elif method.upper() == "POST":
  20. response = requests.post(url, json=data, params=params, cookies=cookies)
  21. else:
  22. raise ValueError("Unsupported HTTP method")
  23. logger.info(f"Calling API: {endpoint}, Method: {method}, Params: {params}, Data: {data}, ResCode:{response.status_code}, ResData: {response.text}")
  24. if response.status_code == 502:
  25. cookies = LoginApi().login_bmc(config.USERNAME, config.PASSWORD)
  26. raise NoValidError()
  27. response.raise_for_status()
  28. return response.json()
  29. except requests.RequestException as e:
  30. print(f"Error calling API {endpoint}: {e}")
  31. logger.warning(f"Calling API: {endpoint}, Method: {method}, Params: {params}, Data: {data}, Error:{e}")
  32. logger.error(f"Failed to call API 3 times: {endpoint}, Method: {method}, Params: {params}, Data: {data}")
  33. raise Exception("Failed to call API 3 times")
  34. def save_json(data, filename):
  35. with open(filename, "w") as f:
  36. f.write(json.dumps(data))