【问题标题】:Is there a way to start/stop a celery task from django views?有没有办法从 django 视图启动/停止芹菜任务?
【发布时间】:2021-04-16 05:30:27
【问题描述】:

我刚刚为我的 django 应用程序完成了 celery 任务,但我现在正在寻找一种方法来通过前端 UI 上的切换按钮来启动/停止它。我知道它可以在 django-admin(内置)上完成。但我想为应用程序制作它。

就像从典型的 django 视图和 restapi 中一样,您可以创建这样的函数:

def start_taskdef stop_task通过api(URL)调用来执行。

我该怎么做?谢谢!

【问题讨论】:

    标签: django django-rest-framework django-views celery django-celery


    【解决方案1】:

    当然,任务只是您需要调用才能启动的函数,如果您有task_id,那么您可以撤销任务。更多信息请参见this answer

    我有一个启动更新搜索索引的任务的示例。

    @app.task
    def update_search():
        """ Update haystack """
        try:
            update_index.Command().handle(
                remove=True, interactive=False, verbosity=2
            )
        except TransportError as e:
            logger.error(e)
    

    这是从使用管理员中的操作链接访问的视图中调用的;

    class UpdateSearchView(View):
        """
        View called from the admin that updates search indexes.
        Checks the requesting user is a super-user before proceeding.
        """
        admin_index = reverse_lazy('admin:index')
    
        @staticmethod
        def _update_search(request):
            """Update search index"""
            update_search.delay()
            messages.success(
                request, _('Search index is now scheduled to be updated')
            )
    
        def get(self, request, *args, **kwargs):
            """Update search, re-direct back the the referring URL"""
            if request.user.is_anonymous() or not request.user.is_superuser:
                raise PermissionDenied
    
            self._update_search(request)
    
            # redirect back to the current page (of index if there is no
            # current page)
            return HttpResponseRedirect(request.GET.get('next', self.admin_index))
    

    【讨论】:

    • 怎么样,如果我只得到task_name 而不是task_id 怎么样。因为 task_id 会更改该 task_name 的每次执行?
    • 是的,ID 显然只是正在运行的任务的唯一实例,因此可以撤销。您不能仅通过任务名称撤消。详情在这里; docs.celeryproject.org/en/stable/reference/…
    猜你喜欢
    • 2018-04-13
    • 2016-09-14
    • 1970-01-01
    • 2013-01-12
    • 2013-05-05
    • 1970-01-01
    • 2021-04-25
    • 2011-05-23
    • 2018-07-04
    相关资源
    最近更新 更多