#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib
import httplib
import unittest
import logging
from contextlib import closing
USERNAME = "Username"
PASSWORD = "Password"
CONNECTION_TIMEOUT = 10 # seconds
SMS_PROVIDERS = ["get1.spiricom.spirius.com", "get2.spiricom.spirius.com"]
def _do_send_sms_request(conn, request):
"""
Send request to HTTP GET API.
Retry if provider tell us we are sending faster than we have agreed.
"""
for attempt in xrange(3):
conn.request("GET", request)
result = conn.getresponse()
if result.status != httplib.CONFLICT:
logging.warning("INFO: Request sent. Response: %s, %s, %s" %
(result.status, result.reason, result.read()))
return result.status
else:
# Provider told us we are sending too fast. Wait then retry.
time.sleep(1.5)
def send_sms(username, password, ext_id, from_type, from_number, to_number, sms_text):
"""
Iterate over all available sms providers and attempt to setup a HTTP connection.
When a connection is established, send request.
If _do_send_sms_request() raises an exception (or connection times out), use next provider
"""
from_number_enc = from_number.encode('iso-8859-1', 'ignore')
sms_text_enc = sms_text.encode('utf-8', 'ignore')
for endpoint in SMS_PROVIDERS:
try:
with closing(httplib.HTTPSConnection("%s:55001" % endpoint, timeout=CONNECTION_TIMEOUT)) as conn:
params = {
'User': username,
'Pass': password,
'To': to_number,
'From': from_number_enc,
'FromType': from_type,
'Msg': sms_text_enc,
'CharSet': 'utf-8'
}
if len(ext_id) > 0:
params['ExtId'] = "List: " + ext_id
request = "/cgi-bin/sendsms?%s" % urllib.urlencode(params)
if _do_send_sms_request(conn, request) == httplib.ACCEPTED:
logging.warning("SMS was accepted")
else:
logging.warning("SMS was NOT accepted")
# Request was successfully sent, so we are done for now
return 1
except Exception, e:
logging.warning("WARNING: Failed to send request, connection problem: %s" % str(e))
pass # retry using next endpoint in list
return 0
class UnitTests(unittest.TestCase):
def test_send_sms(self):
result = send_sms(
username=USERNAME,
password=PASSWORD,
ext_id="",
from_type="I",
from_number="+46123456789",
to_number="+46123456789",
sms_text="Test SMS")
self.assertTrue(result)