Whats the alternative to 'yield' function in Django

1.8k views Asked by At

The 'yield' function streams the output to the browser i.e. it appends the value to the response.

My requirement is that instead of "appending", is there any built in function which overwrites the old value, or just say does not append the new value to the old one..?

To explain my requirement:

following is the function in my "views.py":

def handle_uploaded_file(f):
    filename = "/media/Data/static/Data/" + f.name
    uploaded = 0
    perc = 0.0
    filesize = f.size
    destination = open(filename, 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
        uploaded = uploaded + len(chunk)
        yield(str((uploaded * 100) / filesize) + "% ")
    destination.close()
    yield(f.name + " (" + str(round(f.size/1024.0, 2)) + " KB) uploaded successfully.")

Following is the output of the above function:

2% 4% 7% 9% 11% 14% 16% 18% 21% 23% 25% 28% 30% 32% 35% 37% 39% 42% 44% 46% 49% 51% 53% 56% 58% 60% 63% 65% 67% 70% 72% 74% 77% 79% 81% 84% 86% 89% 91% 93% 96% 98% 100% Butterfly.wmv (2732.16 KB) uploaded successfully.

As you see, the percentage gets appended to the previous passed values, whereas I want to overwrite the old value with the new one.

Is there any built in function for this behaviour in Django/python? Or can I simulate this through code?

Thanks in advance.

2

There are 2 answers

2
Daniel Roseman On BEST ANSWER

You can't overwrite things you've already sent to the browser. This is a remote network connection, remember: once something has been sent, it's been sent.

You'll need to do something clever with javascript or CSS to get the result you want.

2
nvloff On

This response thing looks quite dirty.

Generally speaking most of the time progress bars on file uploads are implemented using JavaScript and a web server module(I used it with Rails) or a JSON view(I used with django ) that returns the status of the upload in JSON. Here are some modules:

  • upload_progress_module for Apache
  • HttpUploadProgressModule for nginx
  • mod_uploadprogress for lighttpd

Note that these modules have Rails in mind. But they should give you an idea how the interface of your json view that returns the progress should look. And have some Java Script examples that you can get a general feeling how things should work on the JS part.