Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I just finished my celery task for my django app, but I'm looking a way now for how to start/stop it through a toggle button on my frontend UI. I know it can do on django-admin(built in). but I want to make it for the app.

like from a typical django view and restapi, you create a function like this:

def start_task and def stop_task and call it through api(URL) to execute it.

How can I do it? Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
259 views
Welcome To Ask or Share your Answers For Others

1 Answer

Sure, a task is just a function you need to call to start and if you've got a task_id then you can revoke a task. More on that explain in this answer

I've got an example of starting a task which updates a search index.

@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)

This is called from a view which is accessed using an action link in the admin;

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...