Home > Net >  How to run long running task behind the scence in django class based view?
How to run long running task behind the scence in django class based view?

Time:01-26

I want to run long running task in Django class based Redirectview. Before this running task to complete I want to return template. Here is my code.

I try with this code.

class Redirect_to_page(RedirectView):
    async def sleep_long(self):
        for i in range(1,10):
            print(f'Run {i}')
            await asyncio.sleep(1)
        pass
    query_string = True
    pattern_name = 'pages:redirect_page'
    
    def get_redirect_url(self, *args, **kwargs):
        asyncio.run(self.sleep_long())
        print('This run before complete!')
        return super().get_redirect_url(*args, **kwargs)

and this is result.

Run 1
Run 2
Run 3
Run 4
Run 5
Run 6
Run 7
Run 8
Run 9
This run before complete!

But I want result like_

Run 1
This run before complete!
Run 2
Run 3
Run 4
Run 5
Run 6
Run 7
Run 8
Run 9

CodePudding user response:

It is not clear based on you question what exactly you are attempting to accomplish. In general, asynchronous tasks can be run by integrating 3rd party workers. Celery is one which is quite popular, and has straight-forward django integrations.

docs here: https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html simple blog post here: https://realpython.com/asynchronous-tasks-with-django-and-celery/

I have had a great experience with celery and would highly recommend.

You can create a task responsible for handling your business logic, and dispatch that task in your view.

  • Related