David Cain
David Cain

Reputation: 17333

Session values not saved until view returns

I have a Django Form that, upon submission, calls a rather time-intensive operation. This operation (a Python function) creates data as it goes.

When relevant data is created, I would like to store it to the active session so that a user can see results as they're generated (via a simple refresh for now).

I've written a template that displays the form and all present fields of the session. However, it seems the session is only saved in full when the long-running function returns (refreshing the page during execution displays none of the modified components). From When sessions are saved, I'm led to believe the session should be updated as soon as the dictionary is modified.

Am I misunderstanding how sessions are saved? Alternatively, is there another way to achieve what I'm looking for?


Below is an abstraction of the relevant views.py code:

def my_form(request):
    """ Render the form, with any results included below. """
    if request.method == "POST":
        form = MyForm(request.POST)
        if form.is_valid():
            request.session.clear()
            long_running_func(request.session, form)
    else:
        form = MyForm()
    return render_to_response('my_form.html', {'form': form,
                                               'session': request.session})

def long_running_func(session, form):
    session["status"] = "Executing"

    result_data = long_running_task()
    session["results"] = result_data

    ...

Upvotes: 0

Views: 94

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599530

You have misunderstood that link. It doesn't say that sessions are saved every time the dictionary is modified. On the contrary, session saving is based on the request: the docs were just explaining that even within a complete request/response cycle, if the dictionary has not been assigned to, it will not be modified.

You probably want to look at the section above, Using sessions out of views, to see how to update the session manually. However, I must say that I think your design is flawed: I can't see how the user is supposed to view the updated session values. Your form processing is done within the original request process, and a refresh will simply interrupt that, potentially leaving the task uncompleted.

Really, you should look into something like Celery to perform long-running processes outside of the request cycle.

Upvotes: 2

Related Questions