EsseTi
EsseTi

Reputation: 4271

Django StreamingHttpResponse into a Template

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

Upvotes: 3

Views: 9267

Answers (1)

Frank
Frank

Reputation: 909

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)

Upvotes: 9

Related Questions