Forums

Execute a function in django asynchronously

I have a web app in which there is a feature, for restoring the data from google drive. When a particular user clicks on the restore button an ajax request is sent and a function inside view.py is executed. During the ongoing process of restoration, the other user who opens up the app will see the maintenance page. But the user which has pressed the restoration button can use the website.

As you might have guessed that, synchronously this cant be possible. When any other user opens the app, the restoration process gets interrupted. The same thing happens when the user who has started the restoration process, decides to use the app (go to another page, click come buttons, etc). So what I want is that when the user presses the restore button the function inside the views.py should execute on a different thread and close that thread when the process finishes. Is there anything pythonanywhere supports in doing so?

Scheduled and always on task cant be used in this because this isn't a recurring task.

Have you seen our help page on that issue yet? Why do you think a long running mamangement command as Always-on task would not work here?

First of all what is Django-Q. Second I didnt think this through. I think Always on task might work. I can make a database having only one column called restore. By default its value will be false. The command on always on task will run endlessly fetching this restore column in a loop. When the user clicks on the restore this value will be changed to true. So when the forever running command on always on task finds that the value is true it will execute the algorithm. But I am confused, as it is always on task, should I use while loop to fetch the restore column or there is no need for the while loop as the program will run again and again?

You should use a while loop -- although always-on tasks will restart if they exit, that's designed to handle cases where a program crashes, so there's a back-off -- if a program keeps exiting quickly, the restarts will get slower and slower so as not to cause system issues due to a constantly crashing program.

I'd also recommend putting a sleep (say, a few seconds) between your polls of the database, so that you don't burn up huge amounts of your CPU quota.

Sure, thank you.

No problem!