18 from typing
import Optional, Any, Dict, List, Union, Tuple, BinaryIO
25 from urllib.parse
import urlsplit, urlunsplit, SplitResult
27 from .network_response
import NetworkResponse
30 logger = logging.getLogger(
"coretexpylib")
33 RequestBodyType = Dict[str, Any]
34 RequestFormType = List[Tuple[str, Tuple[str, Union[bytes, BinaryIO], str]]]
37 def logFilesData(files: Optional[RequestFormType]) -> List[Dict[str, Any]]:
41 debugFilesData: List[Dict[str, Any]] = []
43 for paramName, (fileName, fileData, mimeType)
in files:
44 if isinstance(fileData, bytes):
45 fileSize = len(fileData)
47 fileSize = fileData.seek(0, io.SEEK_END)
50 debugFilesData.append({
51 "paramName": paramName,
60 def logRequestFailure(endpoint: str, response: NetworkResponse) ->
None:
61 if not response.hasFailed():
62 raise ValueError(f
">> [Coretex] Invalid response status code: \"{response.statusCode}\"")
64 logger.debug(f
">> [Coretex] Request to \"{endpoint}\" failed with status code: {response.statusCode}")
67 responseJson = response.getJson(dict)
69 message = responseJson.get(
"message")
70 if message
is not None:
71 logger.debug(f
"\tResponse: {message}")
73 logger.debug(f
"\tResponse: {responseJson}")
74 except (ValueError, TypeError):
75 logger.debug(f
"\tResponse: {response.getContent()!r}")
78 def baseUrl(url: str) -> str:
79 result = urlsplit(url)
80 parsed = SplitResult(result.scheme, result.netloc,
"",
"",
"")
82 return urlunsplit(parsed)
85 def getDelayBeforeRetry(retry: int) -> int:
89 start = (retry + 1) ** 2
90 end = (retry + 2) ** 2
92 return random.randint(start, end)
95 def sleepBeforeRetry(retry: int, endpoint: str) ->
None:
96 delay = getDelayBeforeRetry(retry)
97 logger.debug(f
">> [Coretex] Waiting for {delay} seconds before retrying failed \"{endpoint}\" request")
102 def getTimeoutForRetry(retry: int, timeout: Tuple[int, int], maxTimeout: Tuple[int, int]) -> Tuple[int, int]:
103 connectTimeout, readTimeout = timeout
104 maxConnectTimeout, maxReadTimeout = maxTimeout
107 min(connectTimeout * retry, maxConnectTimeout),
108 min(readTimeout * retry, maxReadTimeout)