3

Django 1.5 is just came out and it ships the StreamingHttpResponse. Now, I've read this discussion and the second answer actually prints out the stream in a page (actually just data).

What I want to do is to print the output of a stream response into a template, not just print the data as in the discussion.

What should I do? do I've to use javascript and call the view that implements the StreamingHttpResponse, or there's a way to tell django to render the template and later send the StreamingHttpResponse data to the template (then I need to know what's the variables where data are stored)?

Edit: the solution I found so far is to write the pieces of the final html page into the generator (yield). The problem of this solution is that I can't have, for example, a bar that grows with the data streamed (like a loading bar).

ciao

Community
  • 1
  • 1
EsseTi
  • 4,079
  • 5
  • 36
  • 63

1 Answers1

9

Yes, but it may not be what you really want, as the entire template will be iterated. However, for what it's worth, you can stream a re-rendered context for a template.

from django.http import StreamingHttpResponse
from django.template import Context, Template

#    Template code parsed once upon creation, so
#        create in module scope for better performance

t = Template('{{ mydata }} <br />\n')

def gen_rendered():
    for x in range(1,11):
        c = Context({'mydata': x})
        yield t.render(c)

def stream_view(request):
    response = StreamingHttpResponse(gen_rendered())
    return response

EDIT: You can also render a template and just append <p> or <tr> tags to it, but it's quite contrary to the purpose of templates in the first place. (i.e. separating presentation from code)

from django.template import loader, Context
from django.http import StreamingHttpResponse

t = loader.get_template('admin/base_site.html') # or whatever
buffer = ' ' * 1024

def gen_rendered():  
    yield t.render(Context({'varname': 'some value', 'buffer': buffer}))
    #                                                 ^^^^^^
    #    embed that {{ buffer }} somewhere in your template 
    #        (unless it's already long enough) to force display

    for x in range(1,11):
        yield '<p>x = {}</p>{}\n'.format(x, buffer)
Frank
  • 899
  • 1
  • 8
  • 13
  • ok, i was already at this point. As far as I understood from this answer and from this Django Google Groups topic[https://groups.google.com/d/msg/django-users/eQ2SVB_uYuE/IayaI0YlPngJ] and replies, what i want to do should not be done in this way. thanks for the help – EsseTi Mar 13 '13 at 12:13
  • 1
    I`m unsure about _shouldn't_. If you have a small project where you're in control of presentation and logic, it seems acceptable to me. I answered it because I was in the middle of implementing it. Note that even if one closes the browser page, the logic (mine is a batch add) continues to run. – Frank Mar 13 '13 at 18:18