import requests import threading import os import time import logging from .request import buildRequest #session = requests.Session() _thread_local = threading.local() #def getSession(): def getSession(reset=False): if reset and hasattr(_thread_local, "session"): _thread_local.session.close() del _thread_local.session if not hasattr(_thread_local, "session"): session = requests.Session() session.name = threading.current_thread().name session.created_at = time.monotonic() _thread_local.session = session return _thread_local.session def executeRequest(action, outputs, resolved): session = getSession() session_log = os.environ.get("LOGS_SESSION", "false").lower() == "true" if session_log: print( f"Session {session.name} used by " f"{threading.current_thread().name} thread" ) for attempt in range(2): request, outputs = buildRequest(action, outputs, resolved) try: response = session.request( method=request["method"], url=request["path"], json=request.get("object"), headers=request.get("headers"), data=request.get("data"), files=request.get("files"), timeout=(10, 30) ) return response, outputs except (requests.Timeout, requests.ConnectionError) as error: #print(f"{type(error).__name__} during {action.name}: {error}") logging.warning(f"{type(error).__name__} during {action.name}: {error}") session = getSession(reset=True) if attempt == 0: logging.warning(f"Retrying {action.name}") return None, outputs