Django中的API中的异步调用 [英] Async call in API made in Django

查看:803
本文介绍了Django中的API中的异步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将DRF与Twilio SMS发送服务一起使用。我在某些对象保存上添加了此代码-我在某些API调用中做了此操作。但是,正如我看到的那样,Django等待Twilio代码被执行(可能等待响应),大约需要1-2秒才能从Twilio服务器获得响应。

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.

我想优化我的API,但是我不确定如何异步发送Twilio SMS请求。这是我的代码。

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")

推荐答案

API调用不是异步的,您需要使用其他方法来使SMS发送异步,您可以使用任何以下内容:

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

这篇关于Django中的API中的异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆