I am working on an alert application using Django and the Twilio api to make calls and messages. I am sending close to 2000 calls and messages, using 20 different phone numbers, using a function similar to the one below:
def call_number(phone_numbers, message_to_broadcast):
# index twilio controls the phone number that the message is being sent from
response = VoiceResponse()
response.say('Hello. this is a test message ' + message_to_broadcast + 'Goodbye.', voice='alice' )
index_twilio= 0
try:
for phones in phone_numbers:
client.calls.create(to=phones,
from_=numbers['twilio_numbers'][index_twilio],
status_callback='https://mywebsite.com//ealert/voicedistribution/',
twiml=response)
index_twilio = (0 if index_twilio >= 19 else index_twilio+1)
except (TwilioRestException):
# A generic 400 or 500 level exception from the Twilio API
continue
When I click on the submit button, my application just keeps loading. I would like to be redirected immediately to my home page and have this function run on the background.
My question is: how do I resume using my application, and be redirected immediately, while the server is still making calls and sending messages in the background? Been looking around but I have not been able to find enough.
Another question is, is it possible to make this faster instead of running both my functions this way:
def main():
call_number(phones, message)
text_number(phones, message)
main()
Any criticism and/or help will be much appreciated!
One way to achieve this is to implement queues. Instead of calling or messaging in the function call, add them to the Queue, redirect to the homepage and then start processing the queue in background. You can use django-celery for this purpose. You can use some other queue processing instead of celery.
Another simple solution is to use django-after-response. Just add a simple decorator to your function and it will process the code after sending response to the user or redirecting to homepage in your case