Python Django update variable in template while function runs in background

Question:

I have this simple template which has a button:

<a class="button" href="{% url 'function' %}">
    <button>
        Settings
    </button>
</a>

And views.py in which I have function definition.

def function(request):

    context = {}
    object = Runner()
    object.prepate_sth()
    context['tasks'] = runner.tasks.remaining

    try:
        thread = threading.Thread(target=runner.run_sth, args=())
        thread.start()
    except Exception:
        raise Exception

    return render(request, 'home.html', context)

I am creating separate thread in order to not to block the function execution and run some other function in the background. That task in the background changes the quantity of elements in runner.tasks.remaining list variable. I would want to have that variable shown in the template and being updated constantly when its value changes. How can I achieve that?

Asked By: Alraku

||

Answers:

You can use the Django Session & Cookies for constantly updating variable values.

Here is the documentation for using session & cookies

Django Cookiew
Django Session

Answered By: Abu Nayem

With Django, the short answer is you cannot. Once the HTML/template is rendered on the client side you cannot change it without refreshing and the current way you have it the thread would restart, so it would always show that initial value.

With Javascript & Websockets, or just a bunch of Javascript Ajax posts every x seconds, you can constantly ping the server and get a reply with the threads progress and update the HTML.. but even this raises problems:

  1. You need to be able to access the var the thread is changing.
  2. You need to keep track of what thread is for what User.

The solution would probably have the thread update the value inside of a cache, with a key like {user}_tasks. The thread will update the cache. The view you would ping would just return the cached value to the JS who then would update the value on the HTML.
You might also want to keep track of if the thread is already running for that user, so if they refresh the page it doesn’t start up another- or it will kill the original and start over.

Or instead of using a cache, well sessions is pretty much a cache, you could use the sessions engine instead of working directly with the cache like @Abu Nayem pointed out.

Either way, this is pretty complicated with a lot of moving parts. I’ve pointed out the main problems you’ll run into, but there’s most likely plenty more

Answered By: Nealium
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.