Async call in API made in Django

萝らか妹 提交于 2019-12-12 03:24:12

问题


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:


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

  • django-background-tasks: Simple and doesn't require a worker
  • python-rq: Great for simple async tasks
  • celery: A more complete solution


来源:https://stackoverflow.com/questions/36385796/async-call-in-api-made-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!