Python 在 Django 中启动后台任务的简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21945052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple approach to launching background task in Django
提问by Marc
I have a Django website, and one page has a button (or link) that when clicked will launch a somewhat long running task. Obviously I want to launch this task as a background task and immediately return a result to the user. I want to implement this using a simple approach that will not require me to install and learn a whole new messaging architecture like Celery for example. I do not want to use Celery! I just want to use a simple approach that I can set up and get running over the next half hour or so. Isn't there a simple way to do this in Django without having to add (yet another) 3rd party package?
我有一个 Django 网站,其中一个页面有一个按钮(或链接),点击后会启动一个运行时间较长的任务。显然我想将此任务作为后台任务启动并立即将结果返回给用户。我想使用一种简单的方法来实现这一点,例如不需要我安装和学习像 Celery 这样的全新消息传递架构。我不想用芹菜!我只想使用一种简单的方法,我可以设置并在接下来的半小时左右开始运行。没有一种简单的方法可以在 Django 中做到这一点,而不必添加(又一个)第 3 方包?
采纳答案by John Lehmann
If you're willing to install a 3rd party library, but you want something a whole lot simpler than Celery, check out Redis Queue. It does require Redis, which is pretty easy in itself, but that can provide a lot of other benefits as well.
如果您愿意安装第 3 方库,但想要比 Celery 简单得多的东西,请查看 Redis Queue。它确实需要 Redis,这本身很容易,但这也可以提供许多其他好处。
RQ itself has almost zero configuration. It's startlingly simple.
RQ 本身几乎为零配置。这非常简单。
References:
参考:
回答by Benjamin Toueg
Just use a thread.
只需使用一个线程。
import threading
t = threading.Thread(target=long_process,
args=args,
kwargs=kwargs)
t.setDaemon(True)
t.start()
return HttpResponse()
See this question for more details: Can Django do multi-thread works?
有关更多详细信息,请参阅此问题: Can Django do multi-thread works?
回答by user226114
Have a look at django-background-tasks- it does exactly what you need and doesn't need any additional services to be running like RabbitMQ or Redis. It manages a task queue in the database and has a Django management command which you can run once or as a cron job.
看看django-background-tasks- 它完全满足您的需求,并且不需要像 RabbitMQ 或 Redis 那样运行任何额外的服务。它管理数据库中的任务队列,并有一个 Django 管理命令,您可以运行一次或作为 cron 作业运行。

