util.py 1.4 KB

12345678910111213141516171819202122232425262728
  1. import requests
  2. from common import config
  3. from common.logger import logger
  4. def req_api(endpoint, method="GET", params=None, data=None, headers=None, cookies=None) -> dict:
  5. """
  6. 通用的API调用方法。
  7. """
  8. for i in range(3):
  9. try:
  10. if method.upper() == "GET":
  11. response = requests.get(endpoint, params=params, cookies=cookies, verify=False, headers=headers)
  12. elif method.upper() == "POST":
  13. response = requests.post(endpoint, json=data, params=params, cookies=cookies, verify=False, headers=headers)
  14. elif method.upper() == "PUT":
  15. response = requests.put(endpoint, json=data, params=params, cookies=cookies, verify=False, headers=headers)
  16. else:
  17. raise ValueError("Unsupported HTTP method")
  18. logger.info(f"Calling API: {endpoint}, Method: {method}, Params: {params}, Data: {data}, ResCode:{response.status_code}, ResData: {response.text}")
  19. response.raise_for_status()
  20. return response.json()
  21. except requests.RequestException as e:
  22. print(f"Error calling API {endpoint}: {e}")
  23. logger.warning(f"Calling API: {endpoint}, Method: {method}, Params: {params}, Data: {data}, Error:{e}")
  24. logger.error(f"Failed to call API 3 times: {endpoint}, Method: {method}, Params: {params}, Data: {data}")
  25. raise Exception("Failed to call API 3 times")