carousallie
carousallie

Reputation: 863

Continuously check if file exists with AJAX in Django

I've developed an application in Django where a user goes to a form on a site and enters in an Elasticsearch query, then generating a report for the user to download. It all works fine and dandy, but lately in testing some more queries we've noticed that some return a lot of results which leads to a timeout request.

What we've figured out that we'd like to do is have Django continuously check if a file exists (because it won't be written to the local system until it's completed) to prevent that timeout issue. Additionally, once the file is done being created we want to add a download button so that the user knows it is done.

Following this tutorial, I added a function to my views.py and associated it with a url which is then called by a javascript code block in my html form. Because I am brand new to using AJAX, JQuery, Javascript, and Django I'm not quite sure how to get it to work. Mainly, I'm trying to figure out how to get it to keep checking if the file is done being created yet. If this were just using basic Python I would do a while loop but I'm unclear how to translate that to JavaScript.

views.py

def check_progress(request):
    """
    Returns whether document generation is complete or in progress
    Returns 0 for in-progress, 1 for complete (either due to completion, or error)
    """
    # check if file exists, return response as a JSON
    file = "/report.docx"
    data = {
        "file_created": path.exists(file)
    }
    return JsonResponse(data)

urls.py

from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('', views.get_query, name='form'),
    path('^ajax/check_progress/$', views.check_progress, name='check_progress')
]  + static(settings.STATIC_URL, document_root=settings.STAT)

form.html

{% block javascript %}
  <script>
    $("#id_username").change(function () {
      var username = $(this).val();

      $.ajax({
        url: '/ajax/check_progress/',
        type: 'HEAD',
        data: {
          'file_exists': 'True'
        },
        dataType: 'json',
        success: function (data) {
          if (data.exists) {
            alert("This file is not yet created");
          }
        }
      });

    });
  </script>
{% endblock %}

Upvotes: 1

Views: 627

Answers (2)

goudarziha
goudarziha

Reputation: 336

You can use setInterval to continually make requests to your backend to see if the file is complete. When it has finished the file, you clear the interval.

var checkInterval = setInterval(isFileComplete, 10000); //10000 is 10 seconds

function isFileComplete() {

    $.ajax({
    url: '/ajax/check_progress/',
    type: 'HEAD',
    data: {
      'file_exists': 'True'
    },
    dataType: 'json',
    success: function (data) {
      if (data.exists) {
        alert("This file is not yet created");

        //add your own flag here to stop interval
        clearInterval(checkInterval);
      }
    }
  });
}

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599698

You can use setTimeout to run your Ajax request at regular intervals

Upvotes: 1

Related Questions