在Djang中呈现页面后在后台执行代码

2024-10-06 07:11:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我和twilio有个剧本:

from twilio.rest import Client

def wa(testo):
    client = Client()
    # this is the Twilio sandbox testing number
    from_whatsapp_number='whatsapp:+14155238886'
    to_whatsapp_number='whatsapp:+39xxxxxxxxxx'
    ts = 'Anomalia Rapportino ' + str(testo)
    client.messages.create(body=ts,
                           from_=from_whatsapp_number,
                           to=to_whatsapp_number)

我在视图中导入了此脚本,并具有以下定义:

def grazieeprint(request, pk):
    intermedio = get_object_or_404(IntermProd, pk=pk)
    datilavoro = WhoWork.objects.get(pk=intermedio.work_id)
    try:
        return render(request, 'FBIsystem/thanksandprint.html', {'pkpreso': pk})

    finally:
        try:
            appo = datilavoro.pezziorastima * 2
            if datilavoro.pezziora >= appo:
                testo = datilavoro.pk
                subprocess.Popen([wa(testo)], shell=True)
        except:
            pass

我需要在django加载页面后运行'wa(testo)',因为发送消息的所有过程大约需要15/20秒。你知道吗

我试着,试着,最后,试着波本郡'但它总是在呈现页面之前发送消息。你知道吗

请帮忙

编辑:

我试着:

    finally:
        try:
            time.sleep(1)
            appo = datilavoro.pezziorastima * 2
            if datilavoro.pezziora >= appo:
                testo = datilavoro.pk
                subprocess.Popen([wa(testo)], shell=True)

它加载页面快,但不发送

编辑2:

试着用芹菜,现在的脚本是:

from twilio.rest import Client
from celery import shared_task,current_task

@shared_task
def wa(testo):
    print 'test'
    client = Client()
    # this is the Twilio sandbox testing number
    from_whatsapp_number='whatsapp:+14155238886'
    to_whatsapp_number='whatsapp:+39xxxxxxxxx'
    ts = 'Anomalia Rapportino ' + str(testo)
    client.messages.create(body=ts,
                           from_=from_whatsapp_number,
                           to=to_whatsapp_number)

但不能并行工作。。。 正确的方法是什么?你知道吗


Tags: tofromimportclientnumberdefwhatsapppk