Django 呼叫管理命令在视图中,但不要等待

use*_*833 5 django django-views django-manage.py

我正在从视图中调用管理命令,如下所示:

from django.http import JsonResponse
from django.core.management import call_command

def index(request):
    call_command('mymanagementcommand')
    response = {'result': 'success',
                'message': 'thank you, come again'}
    return JsonResponse(response)
Run Code Online (Sandbox Code Playgroud)

在继续浏览视图并返回响应之前,我不想等待我的管理命令完成。在这种情况下,“成功”仅表示该命令已被调用,并不关心该命令是否成功运行。

有没有一种 djangoy 方法可以让我在后台启动它而不是等待它?

谢谢!

小智 0

将 call_command 添加到单独的 python 线程。

import threading

class CustomThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        call_command("mymanagementcommand")

def index(request):
   CustomThread().start()

Run Code Online (Sandbox Code Playgroud)