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