Django - flush response?

后端 未结 2 1807
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 10:32

I am sending an AJAX request to a Django view that can potentially take a lot of time. It goes through some well-defined steps, however, so I would like to print status indi

相关标签:
2条回答
  • 2020-12-30 11:25

    I'm not sure you need to use the flush() function.

    Your AJAX request should just go to a django view.

    If your steps can be broken down, keep it simple and create a view for each step. That way one one process completes you can update the user and start the next request via AJAX.

    views.py

    def do_something(request):
        # stuff here
        return HttpResponse()
    
    def do_something_else(request):
        # more stuff
        return HttpResponse()
    
    0 讨论(0)
  • 2020-12-30 11:34

    Most webservers (eg. FCGI/SCGI) do their own buffering, HTTP clients do their own, and so on. It's very difficult to actually get data flushed out in this way and for the client to actually receive it, because it's not a typical operation.

    The closest to what you're trying to do would be to pass an iterator to HttpResponse, and to do the work in a generator; something like this:

    def index(request):
        def do_work():
            step_1()
            yield "step 1 complete"
            step_2()
            yield "step 2 complete"
            step_3()
            yield "step 3 complete"
        return HttpResponse(do_work())
    

    ... but this won't necessarily flush. (Not tested code, but you get the idea; see http://docs.djangoproject.com/en/dev/ref/request-response/#passing-iterators.)

    Most of the infrastructure is simply not expecting a piecemeal response. Even if Django isn't buffering, your front-end server might be, and the client probably is, too. That's why most things use pull updates for this: a separate interface to query the status of a long-running request.

    (I'd like to be able to do reliable push updates for this sort of thing, too...)

    0 讨论(0)
提交回复
热议问题