Connection Error when Sending Multithreaded Requests to an SMS API

43 Views Asked by At

I'm developing a Python script to send SMS messages through an API. I'm using multithreading to reduce the sending time. However, I'm encountering an issue where the connection gets aborted occasionally, despite having exception handling in place.

raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

I've tried using the @retry decorator to make the sending more robust, with a maximum of 10 attempts and a 10-second interval wait. However, the problem persists.

Here's the relevant code snippet:

#Create a semaphore
    sema = asyncio.Semaphore(20)
    
    # task list 
    tasks = []
    # send sms to each row
    for index, row in df.iterrows():
        try:
            task = send_message_CV_async(str(row["Telefono"]),
                                        "34",
                                        "1",
                                        {"valor": [str(row["Cuentacontrato"]),str(row["Deuda"])]},
                                            sema,
                                            sms)
        except Exception as e:
            print(f"Error al enviar el mensaje al telefono {str(row['Telefono'])}: ", e)
            continue
        tasks.append(task)
    
    await asyncio.gather(*tasks)
def send_message_CV(self, tlf: str, id_mensaje:str , dt_variable , datos: dict):
        #message structure dict
        message = {"metodo": "SmsEnvio",
        "id_cbm": "1",
        "id_transaccion": "1",
        "telefono": tlf,
        "id_mensaje": id_mensaje, #Message ID 
        "dt_variable": dt_variable,
         "datos": datos}
        message = json.dumps(message)
        #Send the message
        
        ans = self.send_message_with_retry(self.url, self.headers, message)

        json_ans = json.loads(ans.content)
#tenacity decorator for robustness try 10 times with a 10 seconds wait
    @retry(stop=stop_after_attempt(10), wait=wait_fixed(10))
    def send_message_with_retry(self,url:str, headers:dict, message:str) -> dict:
        
        ans = requests.post(url, headers=headers, data=message)
        ans.raise_for_status()
        return ans

What could be causing this error, and how can I resolve it?

Any help or advice on resolving this connection issue when sending multithreaded requests to the SMS sending API would be greatly appreciated. Thank you in advance!

0

There are 0 best solutions below