yask
yask

Reputation: 4278

How do I make a loading page while I am processing something in the backend with Django?

I have a main view function for my application. After logging in successfully this main view method is called and is expected to render the template.

But I have to perform some calculations in this view method [I am checking certain conditions about the user by making facebook graph api request.]

Thus it takes 2~4 seconds to load.

How do I show this loading scene since the template is rendered by return statement and thus is executed only when the process is complete.

Should I make 2 views , one for showing loading and the other one for calculating and keep making AJAX request to other view method to check if the process is complete or not ?

Upvotes: 3

Views: 1375

Answers (2)

aumo
aumo

Reputation: 5554

You should indeed make two views, one to only return the page showing the loading UI and one to perform the long task.

The second view will be called using an AJAX request made from the "loading" page. The response from the AJAX request will notify your "loading" page that it is time to move on.

You need to make sure the AJAX request's duration won't exceed the timeout of your server (with ~10 seconds, you should be fine).

Upvotes: 2

aumo
aumo

Reputation: 5554

You need to run your Graph API requests in a task executed asynchronously, allowing you to return a HttpResponse without waiting for the task to finish.

Celery will allow you to do just that.

You then need a way to notify your client that the asynchronous task has finished. I see two ways to do that:

  1. Making AJAX requests at regular intervals to a view that will check if the task is finished.
  2. Using WebSockets.

The first approach is the simplest but has the drawback of making a lot of useless requests and of being less reactive.

Using WebSockets on the other side will require more configuration as an external app is required (ex: django-socketio or swampdragon). If it is the only place where you need notifications from server to client, using WebSockets seems to be overkill.

Upvotes: 0

Related Questions