简体   繁体   English

如何使用 Django 在后台运行任务?

[英]How do I run tasks in the background using Django?

I have an end-point in Django which initiates a function which takes really long to complete.我在 Django 有一个端点,它启动一个 function 需要很长时间才能完成。 I don't want the request to wait until this function has been completed.我不希望请求等到这个 function 完成。

def MyRequest(APIView):
    def get(self, request, *args **kwargs):
        a_function_which_takes_really_long_time()
        return Response({"message" : "We're Working on it."})

I tried using asyncio with Django Asynchronous Support .我尝试将 asyncio 与Django Asynchronous Support一起使用。 Also tried python threading here.还在这里尝试了 python 线程。 But all these are making the request to wait until the function is completed.但所有这些都在请求等到 function 完成。

I know that we can easily achieve this using Celery.我知道我们可以使用 Celery 轻松实现这一点。 But that approach would require me to use a message-broker such as Redis, RabbitMQ or any other similar servers which I'm not supposed to use.但是这种方法需要我使用消息代理,例如 Redis、RabbitMQ 或任何其他我不应该使用的类似服务器。

In my opinion using celery with django is really easy and recommended.在我看来,将 celery 与 django 一起使用非常简单且值得推荐。 I am not sure why are you against using a message broker, both of the options you suggested are really stable and wildly used projects.我不确定您为什么反对使用消息代理,您建议的两个选项都是非常稳定且广泛使用的项目。

But, if you still have the broker constraint I can recommend apscheduler which doesn't use an intermediate broker但是,如果您仍然有代理约束,我可以推荐不使用中间代理的apscheduler

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM