Asynchronous view with client update for long runn

2019-05-07 20:41发布

问题:

I have one view in my app that can take quite a long time to be served to the client when requested. In order to inform the user that the server is working I want to present the user some kind like a progress bar, but it is not really a progress bar, it s more like this:

a) client is requesting /myapp/longrunningview/

b) server returns part of the html side, including someting animated that looks like the server is working. At the same time server is calculating the rest of the response, the process which takes very long

c) server finished and returns the response to the client

d) at client side the response is presented

It is not really a progress bar, since the user may request this page from a page outside my app, and I want to return instantly something to the user, without the need to wait for the entire process to be finished. The progress bar implementations that I have found are all based upon some form which is send to the server, while the client showing a progress bar, while waiting for the response.

回答1:

I would use a celery task for this sort of thing. When the user makes the request, start the task and then send back a page with a progress spinner or whatever, then either have a piece of AJAX hit the server every few seconds asking if it's done, or utilize socketio and django-socketio or a similar package to push a "finished" notification to the client, which can then redirect you to wherever you need to go.

Resources:

  • Django-SocketIO https://github.com/stephenmcd/django-socketio
  • SocketIO http://socket.io/
  • Celery http://celeryproject.org/
  • Django-Celery http://docs.celeryproject.org/en/latest/django/index.html