PageRenderTime 9ms CodeModel.GetById 2ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/docs/ref/template-response.txt

https://code.google.com/p/mango-py/
Plain Text | 289 lines | 209 code | 80 blank | 0 comment | 0 complexity | 0caa3a4070327f2fd68cae68a99ccfc7 MD5 | raw file
  1===========================================
  2TemplateResponse and SimpleTemplateResponse
  3===========================================
  4
  5.. versionadded:: 1.3
  6
  7.. module:: django.template.response
  8   :synopsis: Classes dealing with lazy-rendered HTTP responses.
  9
 10Standard :class:`~django.http.HttpResponse` objects are static structures.
 11They are provided with a block of pre-rendered content at time of
 12construction, and while that content can be modified, it isn't in a form that
 13makes it easy to perform modifications.
 14
 15However, it can sometimes be beneficial to allow decorators or
 16middleware to modify a response *after* it has been constructed by the
 17view. For example, you may want to change the template that is used,
 18or put additional data into the context.
 19
 20TemplateResponse provides a way to do just that. Unlike basic
 21:class:`~django.http.HttpResponse` objects, TemplateResponse objects retain
 22the details of the template and context that was provided by the view to
 23compute the response. The final output of the response is not computed until
 24it is needed, later in the response process.
 25
 26SimpleTemplateResponse objects
 27==============================
 28
 29.. class:: SimpleTemplateResponse()
 30
 31Attributes
 32----------
 33
 34.. attribute:: SimpleTemplateResponse.template_name
 35
 36    The name of the template to be rendered. Accepts a
 37    :class:`~django.template.Template` object, a path to a template or list
 38    of template paths.
 39
 40    Example: ``['foo.html', 'path/to/bar.html']``
 41
 42.. attribute:: SimpleTemplateResponse.context_data
 43
 44    The context data to be used when rendering the template. It can be
 45    a dictionary or a context object.
 46
 47    Example: ``{'foo': 123}``
 48
 49.. attribute:: SimpleTemplateResponse.rendered_content
 50
 51    The current rendered value of the response content, using the current
 52    template and context data.
 53
 54.. attribute:: SimpleTemplateResponse.is_rendered
 55
 56    A boolean indicating whether the response content has been rendered.
 57
 58Methods
 59-------
 60
 61.. method:: SimpleTemplateResponse.__init__(template, context=None, mimetype=None, status=None, content_type=None)
 62
 63    Instantiates a
 64    :class:`~django.template.response.SimpleTemplateResponse` object
 65    with the given template, context, MIME type and HTTP status.
 66
 67    ``template``
 68        The full name of a template, or a sequence of template names.
 69        :class:`~django.template.Template` instances can also be used.
 70
 71    ``context``
 72        A dictionary of values to add to the template context. By default,
 73        this is an empty dictionary. :class:`~django.template.Context` objects
 74        are also accepted as ``context`` values.
 75
 76    ``status``
 77        The HTTP Status code for the response.
 78
 79    ``content_type``
 80        An alias for ``mimetype``. Historically, this parameter was only called
 81        ``mimetype``, but since this is actually the value included in the HTTP
 82        ``Content-Type`` header, it can also include the character set encoding,
 83        which makes it more than just a MIME type specification. If ``mimetype``
 84        is specified (not ``None``), that value is used. Otherwise,
 85        ``content_type`` is used. If neither is given,
 86        :setting:`DEFAULT_CONTENT_TYPE` is used.
 87
 88
 89.. method:: SimpleTemplateResponse.resolve_context(context)
 90
 91    Converts context data into a context instance that can be used for
 92    rendering a template. Accepts a dictionary of context data or a
 93    context object. Returns a :class:`~django.template.Context`
 94    instance containing the provided data.
 95
 96    Override this method in order to customize context instantiation.
 97
 98.. method:: SimpleTemplateResponse.resolve_template(template)
 99
100    Resolves the template instance to use for rendering. Accepts a
101    path of a template to use, or a sequence of template paths.
102    :class:`~django.template.Template` instances may also be provided.
103    Returns the :class:`~django.template.Template` instance to be
104    rendered.
105
106    Override this method in order to customize template rendering.
107
108.. method:: SimpleTemplateResponse.add_post_rendering_callback
109
110    Add a callback that will be invoked after rendering has taken
111    place. This hook can be used to defer certain processing
112    operations (such as caching) until after rendering has occurred.
113
114    If the :class:`~django.template.response.SimpleTemplateResponse`
115    has already been rendered, the callback will be invoked
116    immediately.
117
118    When called, callbacks will be passed a single argument -- the
119    rendered :class:`~django.template.response.SimpleTemplateResponse`
120    instance.
121
122    If the callback returns a value that is not `None`, this will be
123    used as the response instead of the original response object (and
124    will be passed to the next post rendering callback etc.)
125
126.. method:: SimpleTemplateResponse.render():
127
128    Sets :attr:`response.content` to the result obtained by
129    :attr:`SimpleTemplateResponse.rendered_content`.
130
131    :meth:`~SimpleTemplateResponse.render()` will only have an effect
132    the first time it is called. On subsequent calls, it will return
133    the result obtained from the first call.
134
135
136TemplateResponse objects
137========================
138
139.. class:: TemplateResponse()
140
141   TemplateResponse is a subclass of
142   :class:`~django.template.response.SimpleTemplateResponse` that uses
143   a :class:`~django.template.RequestContext` instead of
144   a :class:`~django.template.Context`.
145
146Methods
147-------
148
149.. method:: TemplateResponse.__init__(request, template, context=None, mimetype=None, status=None, content_type=None, current_app=None)
150
151    Instantiates an ``TemplateResponse`` object with the given
152    template, context, MIME type and HTTP status.
153
154    ``request``
155        An :class:`~django.http.HttpRequest` instance.
156
157    ``template``
158        The full name of a template, or a sequence of template names.
159        :class:`~django.template.Template` instances can also be used.
160
161    ``context``
162        A dictionary of values to add to the template context. By default,
163        this is an empty dictionary. :class:`~django.template.Context` objects
164        are also accepted as ``context`` values.
165
166    ``status``
167        The HTTP Status code for the response.
168
169    ``content_type``
170        An alias for ``mimetype``. Historically, this parameter was only called
171        ``mimetype``, but since this is actually the value included in the HTTP
172        ``Content-Type`` header, it can also include the character set encoding,
173        which makes it more than just a MIME type specification. If ``mimetype``
174        is specified (not ``None``), that value is used. Otherwise,
175        ``content_type`` is used. If neither is given,
176        :setting:`DEFAULT_CONTENT_TYPE` is used.
177
178    ``current_app``
179        A hint indicating which application contains the current view. See the
180        :ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`
181        for more information.
182
183
184The rendering process
185=====================
186
187Before a :class:`~django.template.response.TemplateResponse` instance can be
188returned to the client, it must be rendered. The rendering process takes the
189intermediate representation of template and context, and turns it into the
190final byte stream that can be served to the client.
191
192There are three circumstances under which a TemplateResponse will be
193rendered:
194
195    * When the TemplateResponse instance is explicitly rendered, using
196      the :meth:`SimpleTemplateResponse.render()` method.
197
198    * When the content of the response is explicitly set by assigning
199      :attr:`response.content`.
200
201    * After passing through template response middleware, but before
202      passing through response middleware.
203
204A TemplateResponse can only be rendered once. The first call to
205:meth:`SimpleTemplateResponse.render` sets the content of the
206response; subsequent rendering calls do not change the response
207content.
208
209However, when :attr:`response.content` is explicitly assigned, the
210change is always applied. If you want to force the content to be
211re-rendered, you can re-evaluate the rendered content, and assign
212the content of the response manually::
213
214    # Set up a rendered TemplateResponse
215    >>> t = TemplateResponse(request, 'original.html', {})
216    >>> t.render()
217    >>> print t.content
218    Original content
219
220    # Re-rendering doesn't change content
221    >>> t.template_name = 'new.html'
222    >>> t.render()
223    >>> print t.content
224    Original content
225
226    # Assigning content does change, no render() call required
227    >>> t.content = t.rendered_content
228    >>> print t.content
229    New content
230
231Post-render callbacks
232---------------------
233
234Some operations -- such as caching -- cannot be performed on an
235unrendered template. They must be performed on a fully complete and
236rendered response.
237
238If you're using middleware, the solution is easy. Middleware provides
239multiple opportunities to process a response on exit from a view. If
240you put behavior in the Response middleware is guaranteed to execute
241after template rendering has taken place.
242
243However, if you're using a decorator, the same opportunities do not
244exist. Any behavior defined in a decorator is handled immediately.
245
246To compensate for this (and any other analogous use cases),
247:class:`TemplateResponse` allows you to register callbacks that will
248be invoked when rendering has completed. Using this callback, you can
249defer critical processing until a point where you can guarantee that
250rendered content will be available.
251
252To define a post-render callback, just define a function that takes
253a single argument -- response -- and register that function with
254the template response::
255
256    def my_render_callback(response):
257        # Do content-sensitive processing
258        do_post_processing()
259
260    def my_view(request):
261        # Create a response
262        response = TemplateResponse(request, 'mytemplate.html', {})
263        # Register the callback
264        response.add_post_render_callback(my_render_callback)
265        # Return the response
266        return response
267
268``my_render_callback()`` will be invoked after the ``mytemplate.html``
269has been rendered, and will be provided the fully rendered
270:class:`TemplateResponse` instance as an argument.
271
272If the template has already been rendered, the callback will be
273invoked immediately.
274
275Using TemplateResponse and SimpleTemplateResponse
276=================================================
277
278A TemplateResponse object can be used anywhere that a normal
279HttpResponse can be used. It can also be used as an alternative to
280calling :meth:`~django.shortcuts.render_to_response()`.
281
282For example, the following simple view returns a
283:class:`TemplateResponse()` with a simple template, and a context
284containing a queryset::
285
286    from django.template.response import TemplateResponse
287
288    def blog_index(request):
289        return TemplateResponse(request, 'entry_list.html', {'entries': Entry.objects.all()})