Async call in API made in Django

2019-09-17 17:30发布

I am using DRF with Twilio SMS sending service. I have added this code on some object save - which I do in some of the API calls. But as I can see Django waits for Twilio code to be executed (which probably waits for response) and it takes around 1-2 seconds to get response from Twilio server.

I would like to optimize my API, but I am not sure how should I send a request for Twilio SMS asynchronously. This is my code.

def send_sms_registration(sender, instance, **kwargs):
    start = int(round(time.time() * 1000))

    if not instance.ignore_sms:
        client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)

        activation_code = instance.activation_code

        client.messages.create(
            to      = instance.phone_number,
            from_   = DEFAULT_SMS_NAME,
            body    = SMS_REGISTRATION_TEXT + activation_code,
        )

    end = int(round(time.time() * 1000))
    print("send_sms_registration")
    print(end - start)



post_save.connect(send_sms_registration, sender=Person, dispatch_uid="send_sms_registration")

Thanks for suggestions!

1条回答
萌系小妹纸
2楼-- · 2019-09-17 17:40

The API call is not asynchronous, you need to use other methods to make sending SMS async, you can use any of the following:

查看更多
登录 后发表回答