Files
notifications-api/app/clients/sms/__init__.py
T

72 lines
2.2 KiB
Python
Raw Normal View History

2022-03-25 13:05:23 +00:00
from time import monotonic
2021-03-10 13:55:06 +00:00
from app.clients import Client, ClientException
2016-02-15 16:01:14 +00:00
class SmsClientResponseException(ClientException):
2016-02-15 16:01:14 +00:00
'''
Base Exception for SmsClientsResponses
2016-02-15 16:01:14 +00:00
'''
def __init__(self, message):
self.message = message
def __str__(self):
2022-03-29 14:18:00 +01:00
return f"SMS client error ({self.message})"
2016-02-15 16:01:14 +00:00
class SmsClient(Client):
'''
Base Sms client for sending smss.
'''
2022-03-25 13:05:23 +00:00
def init_app(self, current_app, statsd_client):
self.current_app = current_app
self.statsd_client = statsd_client
2022-03-25 13:26:16 +00:00
self.from_number = self.current_app.config.get('FROM_NUMBER')
2022-03-25 13:05:23 +00:00
2022-03-24 17:33:45 +00:00
def record_outcome(self, success):
log_message = "Provider request for {} {}".format(
self.name,
"succeeded" if success else "failed",
)
if success:
self.current_app.logger.info(log_message)
self.statsd_client.incr(f"clients.{self.name}.success")
else:
self.statsd_client.incr(f"clients.{self.name}.error")
self.current_app.logger.warning(log_message)
def send_sms(self, to, content, reference, international, sender):
2022-03-25 13:05:23 +00:00
start_time = monotonic()
if sender is None:
# temporary log to see if the following ternary is necessary
# or if it's safe to remove it - keep for 1-2 weeks
self.current_app.logger.warning(
f"send_sms called with 'sender' of 'None' for {reference}"
)
2022-03-25 13:26:16 +00:00
sender = self.from_number if sender is None else sender
2022-03-25 13:05:23 +00:00
try:
response = self.try_send_sms(to, content, reference, international, sender)
self.record_outcome(True)
except SmsClientResponseException as e:
self.record_outcome(False)
raise e
finally:
elapsed_time = monotonic() - start_time
self.statsd_client.timing(f"clients.{self.name}.request-time", elapsed_time)
self.current_app.logger.info("Reach request for {} finished in {}".format(reference, elapsed_time))
return response
def try_send_sms(self, *args, **kwargs):
raise NotImplementedError('TODO Need to implement.')
2016-02-25 11:23:04 +00:00
@property
def name(self):
raise NotImplementedError('TODO Need to implement.')