开发者

Can a Django view return its header first?

开发者 https://www.devze.com 2023-02-14 13:56 出处:网络
I have a particularly heavy view which may need to return a form posting to itself several times, but I need the header straight away.

I have a particularly heavy view which may need to return a form posting to itself several times, but I need the header straight away.

Is there any way for the header portion of the template to be returned first? e.g. my view开发者_JAVA技巧 returns something like:

return HttpResponse(Template('
  {% extends "base.html" %}
  {% block content %} FOO {% endblock %}
'))

Ideally I want to be able to do something like:

partialResponse = request.renderUntilBlock('content')
# lots of work
return partialResponse.extend(Template('
  {% block content %} FOO {% endblock %}
'))

Update: Obviously PHP is structured differently but this is what I'm hoping to emulate:

<?php
echo '<html><head><title>Hi!</title</head><body>';
ob_flush(); flush();
# header has now been output to the client
# do lots of work
echo '<h1>done</h1></body></html>';
?>


Didn't fully test this, but this should work according to the docs.

from django.template import Context, Template

def responder():
    yield '' # to make sure the header is sent

    # do all your work

    t = Template('''
        {% extends "base.html" %}
        {% block content %} FOO {% endblock %}
    ''')
    yield t.render(Context({}))

return HttpResponse(responder())


Yes, it is possible. What you need to do is capture each individual render as a string, then concatenate the strings to form the complete content of the response.

Here is the low-level way:

from django.template import Context, Template
t1 = Template("My name is {{ my_name }}.")
c1 = Context({"my_name": "Adrian"})
s = t.render(c1)
t2 = Template("My name is {{ my_name }}.")
c2 = Context({"my_name": "Adrian"})  # You could also use the same context with each template if you wanted.
s += t.render(c2)

return HttpResponse(s)

However, if you want to do this for performance reasons, I would make sure to compare the time it takes to render all at once versus rendering in pieces. I think rendering all at once is the best way to go in general. You can't return the Response until the entire thing is rendered anyway.


As far as I know, there is no way to do this directly. Your best bet is to simply return a page with just the header and a javascript function that fetches the rest of the page's data via AJAX.

0

精彩评论

暂无评论...
验证码 换一张
取 消