My small Django project only has one view. The user can enter some options and press submit, hence commiting the job that takes >3 minutes. I use redis-queue to carry out the jobs via a background process - the web process simply returns (and renders the .html). All this works. Question is, how can I pass the background's result (filename of file do be downloaded) after completion back into the html so I can display a download button?
I guess I would have to put a small Java / jQuery script into the .html that keeps polling if the job has completed or not (perhaps making use of RQ's on_success / on_failure functions?). However, I'm unsure about the approach. Searching the matter has brought no success (simular issue). Could anyone guide me as to what's the correct way of doing this? I do not intend to use Celery. Ideal solution would be the one providing some code or a clear path. Here's a stripped example:
view.py
from django.shortcuts import render
from django.contrib import messages
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from .forms import ScriptParamForm
from .queue_job import my_job
@csrf_exempt
def home(request):
context = {}
if request.method == 'POST':
if request.POST.get("btn_submit"):
req_dict = dict(request.POST)
form = ScriptParamForm(request.POST)
context['form'] = form
if form.is_valid():
req_dict = dict(request.POST)
job = my_job(outdir=tmp_dir, **req_dict)
context['job'] = job
return render(request, 'webapp/home.html', context)
elif request.POST.get("btn_download"):
serve_file = request.POST.get("btn_download")
with open(serve_file, 'rb') as fp:
response = HttpResponse(fp, headers={
'Content-Type': 'application/zip',
'Content-Disposition': f'attachment; filename="{serve_file}"'
})
return response
else:
form = ScriptParamForm()
context['form'] = form
return render(request, 'webapp/home.html', context)
home.html
{% extends 'base.html' %}
{% block content %}
<form method="POST" autocomplete="on">
{% csrf_token %}
<!-- FORM FIELDS -->
...
<!-- SUBMIT / DOWNLOAD BUTTONS -->
<div>
<button type="submit" name="btn_submit" value="submit" class="btn btn-primary" id="btn-submit">Submit</button>
{% if serve_file %}
<button type="submit" name="btn_download" value={{serve_mode}} class="btn btn-primary">Download</button>
{% endif %}
<span class="not-visible" id="calc-msg"> This may take a few, relax! :) </span>
</div>
</form>
{% endblock content %}
main.js
var x = document.getElementById("btn-submit")
console.log(x)
x.onclick = function () {
$("#calc-msg").removeClass("not-visible");
setInterval(function(){blink()}, 1000);
};
function blink() {
$("#calc-msg").fadeTo(100, 0.1).fadeTo(200, 1.0);
}