From a7e625785f65c41e5a6dc017b31bd0d74821474e Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Tue, 31 May 2011 14:40:05 -0400 Subject: the canonical import location for HTTP exceptions/responses is now pyramid.response --- docs/narr/renderers.rst | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index c3533648b..c7a3d7837 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -73,30 +73,43 @@ When this configuration is added to an application, the which renders view return values to a :term:`JSON` response serialization. Other built-in renderers include renderers which use the :term:`Chameleon` -templating language to render a dictionary to a response. +templating language to render a dictionary to a response. Additional +renderers can be added by developers to the system as necessary (see +:ref:`adding_and_overriding_renderers`). + +Views which use a renderer can vary non-body response attributes (such as +headers and the HTTP status code) by attaching a property to the +``request.response`` attribute See :ref:`request_response_attr`. If the :term:`view callable` associated with a :term:`view configuration` returns a Response object directly (an object with the attributes ``status``, ``headerlist`` and ``app_iter``), any renderer associated with the view configuration is ignored, and the response is passed back to :app:`Pyramid` unchanged. For example, if your view callable returns an instance of the -:class:`pyramid.httpexceptions.HTTPFound` class as a response, no renderer -will be employed. +:class:`pyramid.response.HTTPFound` class as a response, no renderer will be +employed. .. code-block:: python :linenos: - from pyramid.httpexceptions import HTTPFound + from pyramid.response import HTTPFound def view(request): return HTTPFound(location='http://example.com') # any renderer avoided -Views which use a renderer can vary non-body response attributes (such as -headers and the HTTP status code) by attaching a property to the -``request.response`` attribute See :ref:`request_response_attr`. +Likewise for a "plain old response": + +.. code-block:: python + :linenos: + + from pyramid.response import Response + + def view(request): + return Response('OK') # any renderer avoided -Additional renderers can be added by developers to the system as necessary -(see :ref:`adding_and_overriding_renderers`). +Mutations to ``request.response`` in views which return a Response object +like this directly (unless that response *is* ``request.response``) will be +ignored. .. index:: single: renderers (built-in) -- cgit v1.2.3 From 99edc51a3b05309c7f5d98ff96289ec51b1d7660 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Sat, 11 Jun 2011 05:35:27 -0400 Subject: - Pyramid now expects Response objects to have a __call__ method which implements the WSGI application interface instead of the three webob attrs status, headerlist and app_iter. Backwards compatibility exists for code which returns response objects that do not have a __call__. - pyramid.response.Response is no longer an exception (and therefore cannot be raised in order to generate a response). - Changed my mind about moving stuff from pyramid.httpexceptions to pyramid.response. The stuff I moved over has been moved back to pyramid.httpexceptions. --- docs/narr/renderers.rst | 69 +++++++++++++++++++++++++++++++++++++------------ 1 file changed, 53 insertions(+), 16 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index c7a3d7837..99ee14908 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -11,7 +11,6 @@ Response interface, :app:`Pyramid` will attempt to use a .. code-block:: python :linenos: - from pyramid.response import Response from pyramid.view import view_config @view_config(renderer='json') @@ -77,39 +76,52 @@ templating language to render a dictionary to a response. Additional renderers can be added by developers to the system as necessary (see :ref:`adding_and_overriding_renderers`). -Views which use a renderer can vary non-body response attributes (such as -headers and the HTTP status code) by attaching a property to the -``request.response`` attribute See :ref:`request_response_attr`. +Views which use a renderer and return a non-Response value can vary non-body +response attributes (such as headers and the HTTP status code) by attaching a +property to the ``request.response`` attribute See +:ref:`request_response_attr`. If the :term:`view callable` associated with a :term:`view configuration` -returns a Response object directly (an object with the attributes ``status``, -``headerlist`` and ``app_iter``), any renderer associated with the view +returns a Response object directly, any renderer associated with the view configuration is ignored, and the response is passed back to :app:`Pyramid` unchanged. For example, if your view callable returns an instance of the -:class:`pyramid.response.HTTPFound` class as a response, no renderer will be -employed. +:class:`pyramid.response.Response` class as a response, no renderer +will be employed. .. code-block:: python :linenos: - from pyramid.response import HTTPFound + from pyramid.response import Response + from pyramid.view import view_config + @view_config(renderer='json') def view(request): - return HTTPFound(location='http://example.com') # any renderer avoided + return Response('OK') # json renderer avoided -Likewise for a "plain old response": +Likewise for an :term:`HTTP exception` response: .. code-block:: python :linenos: - from pyramid.response import Response + from pyramid.httpexceptions import HTTPNotFound + from pyramid.view import view_config + @view_config(renderer='json') def view(request): - return Response('OK') # any renderer avoided + return HTTPFound(location='http://example.com') # json renderer avoided -Mutations to ``request.response`` in views which return a Response object -like this directly (unless that response *is* ``request.response``) will be -ignored. +You can of course also return the ``request.response`` attribute instead to +avoid rendering: + +.. code-block:: python + :linenos: + + from pyramid.view import view_config + + @view_config(renderer='json') + def view(request): + request.response.body = 'OK' + return request.response # json renderer avoided .. index:: single: renderers (built-in) @@ -377,6 +389,31 @@ callable that uses a renderer, assign the ``status`` attribute to the request.response.status = '404 Not Found' return {'URL':request.URL} +Note that mutations of ``request.response`` in views which return a Response +object directly will have no effect unless the response object returned *is* +``request.response``. For example, the following example calls +``request.response.set_cookie``, but this call will have no effect, because a +different Response object is returned. + +.. code-block:: python + :linenos: + + from pyramid.response import Response + + def view(request): + request.response.set_cookie('abc', '123') # this has no effect + return Response('OK') # because we're returning a different response + +If you mutate ``request.response`` and you'd like the mutations to have an +effect, you must return ``request.response``: + +.. code-block:: python + :linenos: + + def view(request): + request.response.set_cookie('abc', '123') + return request.response + For more information on attributes of the request, see the API documentation in :ref:`request_module`. For more information on the API of ``request.response``, see :class:`pyramid.response.Response`. -- cgit v1.2.3 From d868fff7597c5a05acd1f5c024fc45dde9880413 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Mon, 13 Jun 2011 06:17:00 -0400 Subject: - Remove IResponder abstraction in favor of more general IResponse abstraction. - It is now possible to return an arbitrary object from a Pyramid view callable even if a renderer is not used, as long as a suitable adapter to ``pyramid.interfaces.IResponse`` is registered for the type of the returned object. See the section in the Hooks chapter of the documentation entitled "Changing How Pyramid Treats View Responses". - The Pyramid router now, by default, expects response objects returned from view callables to implement the ``pyramid.interfaces.IResponse`` interface. Unlike the Pyramid 1.0 version of this interface, objects which implement IResponse now must define a ``__call__`` method that accepts ``environ`` and ``start_response``, and which returns an ``app_iter`` iterable, among other things. Previously, it was possible to return any object which had the three WebOb ``app_iter``, ``headerlist``, and ``status`` attributes as a response, so this is a backwards incompatibility. It is possible to get backwards compatibility back by registering an adapter to IResponse from the type of object you're now returning from view callables. See the section in the Hooks chapter of the documentation entitled "Changing How Pyramid Treats View Responses". - The ``pyramid.interfaces.IResponse`` interface is now much more extensive. Previously it defined only ``app_iter``, ``status`` and ``headerlist``; now it is basically intended to directly mirror the ``webob.Response`` API, which has many methods and attributes. - Documentation changes to support above. --- docs/narr/renderers.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 99ee14908..c4a37c23d 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -416,7 +416,7 @@ effect, you must return ``request.response``: For more information on attributes of the request, see the API documentation in :ref:`request_module`. For more information on the API of -``request.response``, see :class:`pyramid.response.Response`. +``request.response``, see :attr:`pyramid.request.Request.response`. .. _response_prefixed_attrs: -- cgit v1.2.3 From c1f3d0fd89eb7f62a7de365ca5c0ef5600ffd900 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Fri, 1 Jul 2011 00:59:11 -0400 Subject: Add JSONP renderer --- docs/narr/renderers.rst | 68 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 18cc8e539..f329a7af9 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -228,6 +228,74 @@ Views which use the JSON renderer can vary non-body response attributes by using the api of the ``request.response`` attribute. See :ref:`request_response_attr`. +.. _jsonp_renderer: + +JSONP Renderer +-------------- + +.. note:: This feature is new in Pyramid 1.1. + +:class:`pyramid.renderers.JSONP` is a `JSONP +`_ renderer factory helper which +implements a hybrid json/jsonp renderer. JSONP is useful for making +cross-domain AJAX requests. + +Unlike other renderers, a JSONP renderer needs to be configured at startup +time "by hand". Configure a JSONP renderer using the +:meth:`pyramid.config.Configurator.add_renderer` method: + +.. code-block:: python + + from pyramid.config import Configurator + + config = Configurator() + config.add_renderer('jsonp', JSONP(param_name='callback')) + +Once this renderer is registered via +:meth:`~pyramid.config.Configurator.add_renderer` as above, you can use +``jsonp`` as the ``renderer=`` parameter to ``@view_config`` or +:meth:`pyramid.config.Configurator.add_view``: + +.. code-block:: python + + from pyramid.view import view_config + + @view_config(renderer='jsonp') + def myview(request): + return {'greeting':'Hello world'} + +When a view is called that uses a JSONP renderer: + +- If there is a parameter in the request's HTTP query string (aka + ``request.GET``) that matches the ``param_name`` of the registered JSONP + renderer (by default, ``callback``), the renderer will return a JSONP + response. + +- If there is no callback parameter in the request's query string, the + renderer will return a 'plain' JSON response. + +Javscript library AJAX functionality will help you make JSONP requests. +For example, JQuery has a `getJSON function +`_, and has equivalent (but more +complicated) functionality in its `ajax function +`_. + +For example (Javascript): + +.. code-block:: javascript + + var api_url = 'http://api.geonames.org/timezoneJSON' + + '?lat=38.301733840000004' + + '&lng=-77.45869621' + + '&username=fred' + + '&callback=?'; + jqhxr = $.getJSON(api_url); + +The string ``callback=?`` above in the the ``url`` param to the JQuery +``getAjax`` function indicates to jQuery that the query should be made as +a JSONP request; the ``callback`` parameter will be automatically filled +in for you and used. + .. index:: pair: renderer; chameleon -- cgit v1.2.3 From 6ce1e0cf1a141767ee0aca70786c15dd993347c5 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Wed, 20 Jul 2011 06:10:38 -0400 Subject: add more index markers --- docs/narr/renderers.rst | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index f329a7af9..572d5855e 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -228,6 +228,9 @@ Views which use the JSON renderer can vary non-body response attributes by using the api of the ``request.response`` attribute. See :ref:`request_response_attr`. +.. index:: + pair: renderer; JSONP + .. _jsonp_renderer: JSONP Renderer @@ -522,9 +525,6 @@ people with older code bases. returning various values in the ``response_headerlist``, this is purely a convenience. -.. index:: - single: renderer (adding) - .. _adding_and_overriding_renderers: Adding and Changing Renderers @@ -550,6 +550,9 @@ The first argument is the renderer name. The second argument is a reference to an implementation of a :term:`renderer factory` or a :term:`dotted Python name` referring to such an object. +.. index:: + pair: renderer; adding + .. _adding_a_renderer: Adding a New Renderer @@ -676,6 +679,9 @@ ending with ``.jinja2`` in its ``renderer`` value. The ``name`` passed to the ``MyJinja2Renderer`` constructor will be the full value that was set as ``renderer=`` in the view configuration. +.. index:: + pair: renderer; changing + Changing an Existing Renderer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -715,6 +721,9 @@ the ``name`` attribute to the renderer tag: config.add_renderer(None, 'mypackage.json_renderer_factory') +.. index:: + pair: renderer; overriding at runtime + Overriding A Renderer At Runtime -------------------------------- -- cgit v1.2.3 From 8cb68208d42899b50025418812bb339f578d553f Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Wed, 20 Jul 2011 07:16:14 -0400 Subject: - Reordered chapters in narrative section for better new user friendliness. - Added more indexing markers to sections in documentation. --- docs/narr/renderers.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 572d5855e..801741c43 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -3,10 +3,10 @@ Renderers ========= -A view needn't *always* return a :term:`Response` object. If a view -happens to return something which does not implement the Pyramid -Response interface, :app:`Pyramid` will attempt to use a -:term:`renderer` to construct a response. For example: +A view callable needn't *always* return a :term:`Response` object. If a view +happens to return something which does not implement the Pyramid Response +interface, :app:`Pyramid` will attempt to use a :term:`renderer` to construct +a response. For example: .. code-block:: python :linenos: -- cgit v1.2.3 From 875ded31e7fdd0c85d1c91458248581b9dd729d7 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Sat, 30 Jul 2011 01:50:24 -0600 Subject: Updated all of the docs to reflect the new pyramid.* settings prefix. --- docs/narr/renderers.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 801741c43..ed391f4fe 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -425,8 +425,9 @@ The above configuration will use the file named ``foo.mak`` in the ``templates`` directory of the ``mypackage`` package. The ``Mako`` template renderer can take additional arguments beyond the -standard ``reload_templates`` setting, see the :ref:`environment_chapter` for -additional :ref:`mako_template_renderer_settings`. +standard ``pyramid.reload_templates`` setting, see the +:ref:`environment_chapter` for additional +:ref:`mako_template_renderer_settings`. .. index:: single: response headers (from a renderer) -- cgit v1.2.3 From 2e7f0cfb4c5f0a4804e0c44cdf181c2ee35b020a Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Wed, 15 Feb 2012 16:18:06 -0500 Subject: remove unused imports --- docs/narr/renderers.rst | 2 -- 1 file changed, 2 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index ed391f4fe..67354a1ed 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -156,7 +156,6 @@ dictionary: .. code-block:: python :linenos: - from pyramid.response import Response from pyramid.view import view_config @view_config(renderer='string') @@ -193,7 +192,6 @@ render the returned dictionary to a JSON serialization: .. code-block:: python :linenos: - from pyramid.response import Response from pyramid.view import view_config @view_config(renderer='json') -- cgit v1.2.3 From 4786cae2e7a053b01091b5e185102f9c26885b08 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Wed, 15 Feb 2012 19:32:46 -0500 Subject: - The system value ``r`` is now supplied to renderers as an alias for ``request``. This means that you can now, for example, in a template, do ``r.route_url(...)`` instead of ``request.route_url(...)``. Fixes #413. --- docs/narr/renderers.rst | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 67354a1ed..1622f1f29 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -333,15 +333,15 @@ dictionary, an error will be raised. Before passing keywords to the template, the keyword arguments derived from the dictionary returned by the view are augmented. The callable object -- -whatever object was used to define the view -- will be automatically -inserted into the set of keyword arguments passed to the template as the -``view`` keyword. If the view callable was a class, the ``view`` keyword -will be an instance of that class. Also inserted into the keywords passed to -the template are ``renderer_name`` (the string used in the ``renderer`` -attribute of the directive), ``renderer_info`` (an object containing -renderer-related information), ``context`` (the context resource of the view -used to render the template), and ``request`` (the request passed to the view -used to render the template). +whatever object was used to define the view -- will be automatically inserted +into the set of keyword arguments passed to the template as the ``view`` +keyword. If the view callable was a class, the ``view`` keyword will be an +instance of that class. Also inserted into the keywords passed to the +template are ``renderer_name`` (the string used in the ``renderer`` attribute +of the directive), ``renderer_info`` (an object containing renderer-related +information), ``context`` (the context resource of the view used to render +the template), and ``request`` (the request passed to the view used to render +the template). ``request`` is also available as ``r`` in Pyramid 1.3+. Here's an example view configuration which uses a Chameleon ZPT renderer: -- cgit v1.2.3 From b2ea4c88b8b3bc9ed657160d8a888780d6c41844 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Wed, 15 Feb 2012 22:06:30 -0500 Subject: Use req instead of r for #413. It's more likely that somebody is already passing something named r, and a template may depend on its existence or nonexistence to conditionalize rendering a bit of html. --- docs/narr/renderers.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 1622f1f29..1f1b1943b 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -341,7 +341,7 @@ template are ``renderer_name`` (the string used in the ``renderer`` attribute of the directive), ``renderer_info`` (an object containing renderer-related information), ``context`` (the context resource of the view used to render the template), and ``request`` (the request passed to the view used to render -the template). ``request`` is also available as ``r`` in Pyramid 1.3+. +the template). ``request`` is also available as ``req`` in Pyramid 1.3+. Here's an example view configuration which uses a Chameleon ZPT renderer: -- cgit v1.2.3 From 0db4a157083d51251b4d3f574a1699fc76359c9d Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Wed, 22 Feb 2012 15:37:50 -0500 Subject: - New API: ``pyramid.config.Configurator.add_notfound_view``. This is a wrapper for ``pyramid.Config.configurator.add_view`` which provides easy append_slash support. It should be preferred over calling ``add_view`` directly with ``context=HTTPNotFound`` as was previously recommended. - New API: ``pyramid.view.notfound_view_config``. This is a decorator constructor like ``pyramid.view.view_config`` that calls ``pyramid.config.Configurator.add_notfound_view`` when scanned. It should be preferred over using ``pyramid.view.view_config`` with ``context=HTTPNotFound`` as was previously recommended. - The older deprecated ``set_notfound_view`` Configurator method is now an alias for the new ``add_notfound_view`` Configurator method. This has the following impact: the ``context`` sent to views with a ``(context, request)`` call signature registered via the deprecated ``add_notfound_view``/``set_notfound_view`` will now be the HTTPNotFound exception object instead of the actual resource context found. Use ``request.context`` to get the actual resource context. It's also recommended to disuse ``set_notfound_view`` in favor of ``add_notfound_view``, despite the aliasing. - The API documentation for ``pyramid.view.append_slash_notfound_view`` and ``pyramid.view.AppendSlashNotFoundViewFactory`` was removed. These names still exist and are still importable, but they are no longer APIs. Use ``pyramid.config.Configurator.add_notfound_view(append_slash=True)`` or ``pyramid.view.notfound_view_config(append_slash=True)`` to get the same behavior. - The ``set_forbidden_view`` method of the Configurator was removed from the documentation. It has been deprecated since Pyramid 1.1. - The AppendSlashNotFoundViewFactory used request.path to match routes. This was wrong because request.path contains the script name, and this would cause it to fail in circumstances where the script name was not empty. It should have used request.path_info, and now does. - Updated the "Registering a Not Found View" section of the "Hooks" chapter, replacing explanations of registering a view using ``add_view`` or ``view_config`` with ones using ``add_notfound_view`` or ``notfound_view_config``. - Updated the "Redirecting to Slash-Appended Routes" section of the "URL Dispatch" chapter, replacing explanations of registering a view using ``add_view`` or ``view_config`` with ones using ``add_notfound_view`` or ``notfound_view_config`` --- docs/narr/renderers.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 1f1b1943b..76035cbdf 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -103,7 +103,7 @@ Likewise for an :term:`HTTP exception` response: .. code-block:: python :linenos: - from pyramid.httpexceptions import HTTPNotFound + from pyramid.httpexceptions import HTTPFound from pyramid.view import view_config @view_config(renderer='json') -- cgit v1.2.3 From d81ea33ac67ac750053acbfd12616db0130de3c8 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Tue, 10 Jan 2012 22:52:24 -0600 Subject: intermediate commit --- docs/narr/renderers.rst | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 76035cbdf..47182c09e 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -177,8 +177,8 @@ using the API of the ``request.response`` attribute. See .. index:: pair: renderer; JSON -``json``: JSON Renderer -~~~~~~~~~~~~~~~~~~~~~~~ +JSON Renderer +~~~~~~~~~~~~~ The ``json`` renderer renders view callable results to :term:`JSON`. It passes the return value through the ``json.dumps`` standard library function, @@ -207,7 +207,10 @@ representing the JSON serialization of the return value: '{"content": "Hello!"}' The return value needn't be a dictionary, but the return value must contain -values serializable by :func:`json.dumps`. +values serializable by :func:`json.dumps`. Extra arguments can be passed +to :func:`json.dumps` by overriding the default renderer. See +:class:`pyramid.renderers.JSON` and +:ref:`_adding_and_overriding_renderers` for more information. You can configure a view to use the JSON renderer by naming ``json`` as the ``renderer`` argument of a view configuration, e.g. by using @@ -221,7 +224,6 @@ You can configure a view to use the JSON renderer by naming ``json`` as the context='myproject.resources.Hello', renderer='json') - Views which use the JSON renderer can vary non-body response attributes by using the api of the ``request.response`` attribute. See :ref:`request_response_attr`. -- cgit v1.2.3 From ba60524b56a639ecad42f85b63af2120d9d96cdc Mon Sep 17 00:00:00 2001 From: Wayne Witzel III Date: Wed, 28 Mar 2012 12:03:52 -0400 Subject: JSON-API rework and Object.__json__ support --- docs/narr/renderers.rst | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 47182c09e..52e97d091 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -212,6 +212,13 @@ to :func:`json.dumps` by overriding the default renderer. See :class:`pyramid.renderers.JSON` and :ref:`_adding_and_overriding_renderers` for more information. +Custom objects can be easily serialized by defining a :func:`__json__` method +on the object. This method should return values serializable by +:func:`json_dumps`. By defining this method and using a :term:`JSON` +renderer the :class:`pyramid.renderers.ObjectJSONEncoder` class will be used +for encoding your object. If you later define your own custom encoder it will +override :class:`pyramid.renderers.ObjectJSONEncoder`. + You can configure a view to use the JSON renderer by naming ``json`` as the ``renderer`` argument of a view configuration, e.g. by using :meth:`~pyramid.config.Configurator.add_view`: -- cgit v1.2.3 From de797c4cefb03f16cfe3505c85d94c0af24eb066 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Thu, 29 Mar 2012 04:21:30 -0400 Subject: - Coverage and docs updates for custom JSON class. - Fork point: master now represents a future 1.4 release. --- docs/narr/renderers.rst | 68 ++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 56 insertions(+), 12 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 52e97d091..34bee3c7f 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -207,17 +207,13 @@ representing the JSON serialization of the return value: '{"content": "Hello!"}' The return value needn't be a dictionary, but the return value must contain -values serializable by :func:`json.dumps`. Extra arguments can be passed -to :func:`json.dumps` by overriding the default renderer. See -:class:`pyramid.renderers.JSON` and -:ref:`_adding_and_overriding_renderers` for more information. - -Custom objects can be easily serialized by defining a :func:`__json__` method -on the object. This method should return values serializable by -:func:`json_dumps`. By defining this method and using a :term:`JSON` -renderer the :class:`pyramid.renderers.ObjectJSONEncoder` class will be used -for encoding your object. If you later define your own custom encoder it will -override :class:`pyramid.renderers.ObjectJSONEncoder`. +values serializable by ``json.dumps``. + +.. note:: + + Extra arguments can be passed to ``json.dumps`` by overriding the default + ``json`` renderer. See :class:`pyramid.renderers.JSON` and + :ref:`adding_and_overriding_renderers` for more information. You can configure a view to use the JSON renderer by naming ``json`` as the ``renderer`` argument of a view configuration, e.g. by using @@ -235,13 +231,57 @@ Views which use the JSON renderer can vary non-body response attributes by using the api of the ``request.response`` attribute. See :ref:`request_response_attr`. +.. _json_serializing_custom_objects: + +Serializing Custom Objects +++++++++++++++++++++++++++ + +Custom objects can be made easily JSON-serializable in Pyramid by defining a +``__json__`` method on the object's class. This method should return values +natively serializable by ``json.dumps`` (such as ints, lists, dictionaries, +strings, and so forth). + +.. code-block:: python + :linenos: + + from pyramid.view import view_config + + class MyObject(object): + def __init__(self, x): + self.x = x + + def __json__(self): + return {'x':self.x} + + @view_config(renderer='json') + def objects(request): + return [MyObject(1), MyObject(2)] + + # the JSON value returned by ``objects`` will be: + # [{"x": 1}, {"x": 2}] + +.. note:: + + Honoring the ``__json__`` method of custom objects is a feature new in + Pyramid 1.4. + +.. warning:: + + The machinery which performs the ``__json__`` method-calling magic is in + the :class:`pyramid.renderers.ObjectJSONEncoder` class. This class will + be used for encoding any non-basic Python object when you use the default + ```json`` or ``jsonp`` renderers. But if you later define your own custom + JSON renderer and pass it a "cls" argument signifying a different encoder, + the encoder you pass will override Pyramid's use of + :class:`pyramid.renderers.ObjectJSONEncoder`. + .. index:: pair: renderer; JSONP .. _jsonp_renderer: JSONP Renderer --------------- +~~~~~~~~~~~~~~ .. note:: This feature is new in Pyramid 1.1. @@ -306,6 +346,10 @@ The string ``callback=?`` above in the the ``url`` param to the JQuery a JSONP request; the ``callback`` parameter will be automatically filled in for you and used. +The same custom-object serialization scheme defined used for a "normal" JSON +renderer in :ref:`json_serializing_custom_objects` can be used when passing +values to a JSONP renderer too. + .. index:: pair: renderer; chameleon -- cgit v1.2.3 From 1f0d9d2193bb9557d4475885776b5679c8dbfa23 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Mon, 16 Apr 2012 23:19:14 -0500 Subject: docs for json defaults --- docs/narr/renderers.rst | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 34bee3c7f..50349c409 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -223,9 +223,9 @@ You can configure a view to use the JSON renderer by naming ``json`` as the :linenos: config.add_view('myproject.views.hello_world', - name='hello', - context='myproject.resources.Hello', - renderer='json') + name='hello', + context='myproject.resources.Hello', + renderer='json') Views which use the JSON renderer can vary non-body response attributes by using the api of the ``request.response`` attribute. See @@ -260,20 +260,21 @@ strings, and so forth). # the JSON value returned by ``objects`` will be: # [{"x": 1}, {"x": 2}] -.. note:: +If you don't own the objects being serialized, it's difficult to add a custom +``__json__`` method to the object. In this case, a callback can be supplied +to the renderer which is invoked when other options have failed. - Honoring the ``__json__`` method of custom objects is a feature new in - Pyramid 1.4. +.. code-block:: python + :linenos: + + def default(obj): + if isinstance(obj, datetime.datetime): + return obj.isoformat() + raise TypeError -.. warning:: +.. note:: - The machinery which performs the ``__json__`` method-calling magic is in - the :class:`pyramid.renderers.ObjectJSONEncoder` class. This class will - be used for encoding any non-basic Python object when you use the default - ```json`` or ``jsonp`` renderers. But if you later define your own custom - JSON renderer and pass it a "cls" argument signifying a different encoder, - the encoder you pass will override Pyramid's use of - :class:`pyramid.renderers.ObjectJSONEncoder`. + Serializing custom objects is a feature new in Pyramid 1.4. .. index:: pair: renderer; JSONP -- cgit v1.2.3 From 18410a6d9d64786f272268db6368981955ff9f10 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Tue, 17 Apr 2012 04:59:33 -0400 Subject: default_encode->_default_encode, dumps->_dumps, massage docs --- docs/narr/renderers.rst | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 50349c409..02063a112 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -177,6 +177,8 @@ using the API of the ``request.response`` attribute. See .. index:: pair: renderer; JSON +.. _json_renderer: + JSON Renderer ~~~~~~~~~~~~~ @@ -260,17 +262,34 @@ strings, and so forth). # the JSON value returned by ``objects`` will be: # [{"x": 1}, {"x": 2}] -If you don't own the objects being serialized, it's difficult to add a custom -``__json__`` method to the object. In this case, a callback can be supplied -to the renderer which is invoked when other options have failed. +If you aren't the author of the objects being serialized, it won't be +possible (or at least not reasonable) to add a custom ``__json__`` method to +to their classes in order to influence serialization. If the object passed +to the renderer is not a serializable type, and has no ``__json__`` method, +usually a :exc:`TypeError` will be raised during serialization. You can +change this behavior by creating a JSON renderer with a "default" function +which tries to "sniff" at the object, and returns a valid serialization (a +string) or raises a TypeError if it can't determine what to do with the +object. A short example follows: .. code-block:: python :linenos: + from pyramid.renderers import JSON + def default(obj): if isinstance(obj, datetime.datetime): return obj.isoformat() - raise TypeError + raise TypeError('%r is not serializable % (obj,)) + + json_renderer = JSON(default=default) + + # then during configuration .... + config = Configurator() + config.add_renderer('json', json_renderer) + +See :class:`pyramid.renderers.JSON` and +:ref:`adding_and_overriding_renderers` for more information. .. note:: -- cgit v1.2.3 From 677216d2c4ddc5f0df857b8f9e8fa6ccfd5fd55a Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Wed, 18 Apr 2012 00:50:10 -0500 Subject: reverted back to using a component registry during json encoding --- docs/narr/renderers.rst | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 02063a112..c36caeb87 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -182,10 +182,10 @@ using the API of the ``request.response`` attribute. See JSON Renderer ~~~~~~~~~~~~~ -The ``json`` renderer renders view callable results to :term:`JSON`. It -passes the return value through the ``json.dumps`` standard library function, -and wraps the result in a response object. It also sets the response -content-type to ``application/json``. +The ``json`` renderer renders view callable results to :term:`JSON`. By +default, it passes the return value through the ``json.dumps`` standard +library function, and wraps the result in a response object. It also sets +the response content-type to ``application/json``. Here's an example of a view that returns a dictionary. Since the ``json`` renderer is specified in the configuration for this view, the view will @@ -209,11 +209,11 @@ representing the JSON serialization of the return value: '{"content": "Hello!"}' The return value needn't be a dictionary, but the return value must contain -values serializable by ``json.dumps``. +values serializable by the configured serializer (by default ``json.dumps``). .. note:: - Extra arguments can be passed to ``json.dumps`` by overriding the default + Extra arguments can be passed to the serializer by overriding the default ``json`` renderer. See :class:`pyramid.renderers.JSON` and :ref:`adding_and_overriding_renderers` for more information. @@ -240,8 +240,8 @@ Serializing Custom Objects Custom objects can be made easily JSON-serializable in Pyramid by defining a ``__json__`` method on the object's class. This method should return values -natively serializable by ``json.dumps`` (such as ints, lists, dictionaries, -strings, and so forth). +natively JSON-serializable (such as ints, lists, dictionaries, strings, and +so forth). .. code-block:: python :linenos: @@ -267,22 +267,18 @@ possible (or at least not reasonable) to add a custom ``__json__`` method to to their classes in order to influence serialization. If the object passed to the renderer is not a serializable type, and has no ``__json__`` method, usually a :exc:`TypeError` will be raised during serialization. You can -change this behavior by creating a JSON renderer with a "default" function -which tries to "sniff" at the object, and returns a valid serialization (a -string) or raises a TypeError if it can't determine what to do with the -object. A short example follows: +change this behavior by creating a custom JSON renderer and adding adapters +to handle custom types. The renderer will attempt to adapt non-serializable +objects using the registered adapters. It will raise a :exc:`TypeError` if it +can't determine what to do with the object. A short example follows: .. code-block:: python :linenos: from pyramid.renderers import JSON - def default(obj): - if isinstance(obj, datetime.datetime): - return obj.isoformat() - raise TypeError('%r is not serializable % (obj,)) - - json_renderer = JSON(default=default) + json_renderer = JSON() + json_renderer.add_adapter(datetime.datetime, lambda x: x.isoformat()) # then during configuration .... config = Configurator() -- cgit v1.2.3 From e012aa12760f6c29bfc9967c50a51d3f47db47da Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Thu, 3 May 2012 02:42:55 -0400 Subject: allow __json__ and custom adapters to accept request arg --- docs/narr/renderers.rst | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index c36caeb87..57b5bc65b 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -241,7 +241,8 @@ Serializing Custom Objects Custom objects can be made easily JSON-serializable in Pyramid by defining a ``__json__`` method on the object's class. This method should return values natively JSON-serializable (such as ints, lists, dictionaries, strings, and -so forth). +so forth). It should accept a single additional argument, ``request``, which +will be the active request object at render time. .. code-block:: python :linenos: @@ -252,7 +253,7 @@ so forth). def __init__(self, x): self.x = x - def __json__(self): + def __json__(self, request): return {'x':self.x} @view_config(renderer='json') @@ -269,8 +270,7 @@ to the renderer is not a serializable type, and has no ``__json__`` method, usually a :exc:`TypeError` will be raised during serialization. You can change this behavior by creating a custom JSON renderer and adding adapters to handle custom types. The renderer will attempt to adapt non-serializable -objects using the registered adapters. It will raise a :exc:`TypeError` if it -can't determine what to do with the object. A short example follows: +objects using the registered adapters. A short example follows: .. code-block:: python :linenos: @@ -278,12 +278,19 @@ can't determine what to do with the object. A short example follows: from pyramid.renderers import JSON json_renderer = JSON() - json_renderer.add_adapter(datetime.datetime, lambda x: x.isoformat()) + def datetime_adapter(obj, request): + return obj.isoformat() + json_renderer.add_adapter(datetime.datetime, datetime_adapter) # then during configuration .... config = Configurator() config.add_renderer('json', json_renderer) +The adapter should accept two arguments: the object needing to be serialized +and ``request``, which will be the current request object at render time. +The adapter should raise a :exc:`TypeError` if it can't determine what to do +with the object. + See :class:`pyramid.renderers.JSON` and :ref:`adding_and_overriding_renderers` for more information. -- cgit v1.2.3 From cc8962d5da32bb30bbfc37c96286282b5ed751ff Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Wed, 29 Aug 2012 17:21:14 -0400 Subject: add newness markers --- docs/narr/renderers.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 57b5bc65b..63287e2cd 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -306,7 +306,9 @@ See :class:`pyramid.renderers.JSON` and JSONP Renderer ~~~~~~~~~~~~~~ -.. note:: This feature is new in Pyramid 1.1. +.. note:: + + This feature is new in Pyramid 1.1. :class:`pyramid.renderers.JSONP` is a `JSONP `_ renderer factory helper which -- cgit v1.2.3 From a2b3e2847ba6e09bf24c1e455dda96b35a090b50 Mon Sep 17 00:00:00 2001 From: Carlos de la Guardia Date: Fri, 2 Nov 2012 00:06:58 -0600 Subject: typo --- docs/narr/renderers.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 63287e2cd..1158d2225 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -329,7 +329,7 @@ time "by hand". Configure a JSONP renderer using the Once this renderer is registered via :meth:`~pyramid.config.Configurator.add_renderer` as above, you can use ``jsonp`` as the ``renderer=`` parameter to ``@view_config`` or -:meth:`pyramid.config.Configurator.add_view``: +:meth:`pyramid.config.Configurator.add_view`: .. code-block:: python -- cgit v1.2.3 From 08c2217e7f831379016e1ddee0b5d51eeca53878 Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Tue, 1 Jan 2013 23:56:02 +0200 Subject: eliminate repeated "the" words --- docs/narr/renderers.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 1158d2225..9017156a6 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -366,7 +366,7 @@ For example (Javascript): '&callback=?'; jqhxr = $.getJSON(api_url); -The string ``callback=?`` above in the the ``url`` param to the JQuery +The string ``callback=?`` above in the ``url`` param to the JQuery ``getAjax`` function indicates to jQuery that the query should be made as a JSONP request; the ``callback`` parameter will be automatically filled in for you and used. -- cgit v1.2.3 From 043ccddb909327106264d10ed5d413760a51770d Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Wed, 2 Jan 2013 02:22:52 +0200 Subject: eliminate other repeated words --- docs/narr/renderers.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 9017156a6..ecf625251 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -264,7 +264,7 @@ will be the active request object at render time. # [{"x": 1}, {"x": 2}] If you aren't the author of the objects being serialized, it won't be -possible (or at least not reasonable) to add a custom ``__json__`` method to +possible (or at least not reasonable) to add a custom ``__json__`` method to their classes in order to influence serialization. If the object passed to the renderer is not a serializable type, and has no ``__json__`` method, usually a :exc:`TypeError` will be raised during serialization. You can -- cgit v1.2.3 From 1e7d75e55428127865cd8bf18576fd71bdf7e5ee Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Mon, 21 Jan 2013 00:03:25 +0200 Subject: fix typos --- docs/narr/renderers.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index ecf625251..5379a4a99 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -823,8 +823,8 @@ sets an ``override_renderer`` attribute on the request itself, which is the .. code-block:: python :linenos: - from pyramid.event import subscriber - from pyramid.event import NewRequest + from pyramid.events import subscriber + from pyramid.events import NewRequest @subscriber(NewRequest) def set_xmlrpc_params(event): -- cgit v1.2.3 From 2b126ef15ee7d8457592faea02f837cf2a6062d4 Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Tue, 22 Jan 2013 07:51:49 +0200 Subject: consistency fixes --- docs/narr/renderers.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 5379a4a99..794e3cffa 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -73,13 +73,13 @@ which renders view return values to a :term:`JSON` response serialization. Other built-in renderers include renderers which use the :term:`Chameleon` templating language to render a dictionary to a response. Additional -renderers can be added by developers to the system as necessary (see -:ref:`adding_and_overriding_renderers`). +renderers can be added by developers to the system as necessary. +See :ref:`adding_and_overriding_renderers`. Views which use a renderer and return a non-Response value can vary non-body response attributes (such as headers and the HTTP status code) by attaching a -property to the ``request.response`` attribute See -:ref:`request_response_attr`. +property to the ``request.response`` attribute. +See :ref:`request_response_attr`. If the :term:`view callable` associated with a :term:`view configuration` returns a Response object directly, any renderer associated with the view -- cgit v1.2.3 From b515ddcf759ebe267b9ee74a1d5af72da8639ae0 Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Wed, 23 Jan 2013 21:56:28 +0200 Subject: displaying line numbers for 1-line snippets is overkill --- docs/narr/renderers.rst | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 794e3cffa..5391a6669 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -63,7 +63,6 @@ the ``renderer`` attribute. For example, this call to with a view callable: .. code-block:: python - :linenos: config.add_view('myproject.views.my_view', renderer='json') @@ -166,7 +165,6 @@ The body of the response returned by such a view will be a string representing the ``str()`` serialization of the return value: .. code-block:: python - :linenos: {'content': 'Hello!'} @@ -204,7 +202,6 @@ The body of the response returned by such a view will be a string representing the JSON serialization of the return value: .. code-block:: python - :linenos: '{"content": "Hello!"}' @@ -619,7 +616,6 @@ For example, to add a renderer which renders views which have a ``renderer`` attribute that is a path that ends in ``.jinja2``: .. code-block:: python - :linenos: config.add_renderer('.jinja2', 'mypackage.MyJinja2Renderer') @@ -725,10 +721,8 @@ Here's an example of the registration of a more complicated renderer factory, which expects to be passed a filesystem path: .. code-block:: python - :linenos: - config.add_renderer(name='.jinja2', - factory='my.package.MyJinja2Renderer') + config.add_renderer(name='.jinja2', factory='my.package.MyJinja2Renderer') Adding the above code to your application startup will allow you to use the ``my.package.MyJinja2Renderer`` renderer factory implementation in view @@ -769,7 +763,6 @@ extension for the same kinds of templates. For example, to associate the :meth:`pyramid.config.Configurator.add_renderer` method: .. code-block:: python - :linenos: config.add_renderer('.zpt', 'pyramid.chameleon_zpt.renderer_factory') @@ -781,7 +774,6 @@ rendered via a Chameleon ZPT page template renderer, use a variation on the following in your application's startup code: .. code-block:: python - :linenos: config.add_renderer('.pt', 'mypackage.pt_renderer') @@ -794,7 +786,6 @@ ones which do not possess a ``renderer`` attribute), pass ``None`` as the ``name`` attribute to the renderer tag: .. code-block:: python - :linenos: config.add_renderer(None, 'mypackage.json_renderer_factory') -- cgit v1.2.3 From 5ed0d3df82787f95338a0dffa8c6a56efb28c6ee Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Wed, 23 Jan 2013 21:59:46 +0200 Subject: use 'versionadded' Sphinx directive --- docs/narr/renderers.rst | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 5391a6669..deb0f6ee8 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -291,9 +291,8 @@ with the object. See :class:`pyramid.renderers.JSON` and :ref:`adding_and_overriding_renderers` for more information. -.. note:: - - Serializing custom objects is a feature new in Pyramid 1.4. +.. versionadded:: 1.4 + Serializing custom objects. .. index:: pair: renderer; JSONP @@ -303,9 +302,7 @@ See :class:`pyramid.renderers.JSON` and JSONP Renderer ~~~~~~~~~~~~~~ -.. note:: - - This feature is new in Pyramid 1.1. +.. versionadded:: 1.1 :class:`pyramid.renderers.JSONP` is a `JSONP `_ renderer factory helper which -- cgit v1.2.3 From 2947141248946db191843c5bc1629c60e7ad8f3a Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Wed, 23 Jan 2013 22:00:10 +0200 Subject: user 'deprecated' Sphinx directive --- docs/narr/renderers.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index deb0f6ee8..b7d3479dc 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -565,7 +565,8 @@ in :ref:`request_module`. For more information on the API of Deprecated Mechanism to Vary Attributes of Rendered Responses ------------------------------------------------------------- -.. warning:: This section describes behavior deprecated in Pyramid 1.1. +.. deprecated:: 1.1 + The behavior described in this entire section. In previous releases of Pyramid (1.0 and before), the ``request.response`` attribute did not exist. Instead, Pyramid required users to set special -- cgit v1.2.3 From 531a2ad34ab0a806513681cddd5d99e50a31c4c6 Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Wed, 23 Jan 2013 22:01:56 +0200 Subject: provide a link to the class; lineno for a 1-liner is overkill --- docs/narr/renderers.rst | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index b7d3479dc..863932e83 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -683,12 +683,10 @@ There are essentially two different kinds of renderer factories: :term:`package`. Here's an example of the registration of a simple renderer factory via -:meth:`~pyramid.config.Configurator.add_renderer`: +:meth:`~pyramid.config.Configurator.add_renderer`, where ``config`` +is an instance of :meth:`pyramid.config.Configurator`: .. code-block:: python - :linenos: - - # config is an instance of pyramid.config.Configurator config.add_renderer(name='amf', factory='my.package.MyAMFRenderer') -- cgit v1.2.3 From 0d40143635c5a248453b881247db66d2ba1f8d00 Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Sat, 9 Feb 2013 14:17:56 +0200 Subject: avoid repetition; the heading already mentions that this stuff is deprecated --- docs/narr/renderers.rst | 3 --- 1 file changed, 3 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 863932e83..34b9ad00c 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -565,9 +565,6 @@ in :ref:`request_module`. For more information on the API of Deprecated Mechanism to Vary Attributes of Rendered Responses ------------------------------------------------------------- -.. deprecated:: 1.1 - The behavior described in this entire section. - In previous releases of Pyramid (1.0 and before), the ``request.response`` attribute did not exist. Instead, Pyramid required users to set special ``response_`` -prefixed attributes of the request to influence response -- cgit v1.2.3 From 8c952d940272d883169973833ca215ac3248e94e Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Wed, 13 Feb 2013 18:28:37 -0600 Subject: add import in code block --- docs/narr/renderers.rst | 1 + 1 file changed, 1 insertion(+) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 34b9ad00c..08ebd881e 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -316,6 +316,7 @@ time "by hand". Configure a JSONP renderer using the .. code-block:: python from pyramid.config import Configurator + from pyramid.renderers import JSONP config = Configurator() config.add_renderer('jsonp', JSONP(param_name='callback')) -- cgit v1.2.3 From eb4ef09189bcc02559c1cfa49bf9be85bc2fbed9 Mon Sep 17 00:00:00 2001 From: Catalin Iacob Date: Sun, 24 Feb 2013 17:45:43 +0100 Subject: Fix wrong reference to non existent getAjax function --- docs/narr/renderers.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 08ebd881e..a9a2aa42a 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -362,7 +362,7 @@ For example (Javascript): jqhxr = $.getJSON(api_url); The string ``callback=?`` above in the ``url`` param to the JQuery -``getAjax`` function indicates to jQuery that the query should be made as +``getJSON`` function indicates to jQuery that the query should be made as a JSONP request; the ``callback`` parameter will be automatically filled in for you and used. -- cgit v1.2.3 From 172c98d010d10080e6cb0b1076eb703af7bd7c76 Mon Sep 17 00:00:00 2001 From: Catalin Iacob Date: Sun, 24 Feb 2013 18:22:05 +0100 Subject: my.package.MyJinja2Renderer is registered for .jinja2 files not .jinja --- docs/narr/renderers.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index a9a2aa42a..b4eb95186 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -720,7 +720,7 @@ factory, which expects to be passed a filesystem path: Adding the above code to your application startup will allow you to use the ``my.package.MyJinja2Renderer`` renderer factory implementation in view -configurations by referring to any ``renderer`` which *ends in* ``.jinja`` in +configurations by referring to any ``renderer`` which *ends in* ``.jinja2`` in the ``renderer`` attribute of a :term:`view configuration`: .. code-block:: python -- cgit v1.2.3 From 8741e9a0e11adbbf58d360f115fb6ad99a76a76e Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Mon, 22 Apr 2013 21:08:00 +0200 Subject: no need to link to a chapter that follows immediately --- docs/narr/renderers.rst | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index b4eb95186..9f7390449 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -38,9 +38,7 @@ object from a view that is configured with a renderer, the renderer is bypassed entirely. Various types of renderers exist, including serialization renderers -and renderers which use templating systems. See also -:ref:`views_which_use_a_renderer`. - +and renderers which use templating systems. .. index:: single: renderer -- cgit v1.2.3 From 8104c862d38c4b823fe913b4a7c04161ebba5bbb Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Mon, 22 Apr 2013 21:12:00 +0200 Subject: simplify explanation The sentence was simply too long-winded (and not too clear). --- docs/narr/renderers.rst | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 9f7390449..9d6509b78 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -33,8 +33,7 @@ by the view must be compatible with the particular kind of renderer used, or an error may occur during view invocation. One exception exists: it is *always* OK to return a Response object, even -when a ``renderer`` is configured. If a view callable returns a response -object from a view that is configured with a renderer, the renderer is +when a ``renderer`` is configured. In such cases, the renderer is bypassed entirely. Various types of renderers exist, including serialization renderers -- cgit v1.2.3 From 61b021633fd6d5e9a5773f5409858b3998e48ca0 Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Mon, 22 Apr 2013 21:18:06 +0200 Subject: grammar --- docs/narr/renderers.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index b4eb95186..8c88fd055 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -51,8 +51,8 @@ and renderers which use templating systems. See also Writing View Callables Which Use a Renderer ------------------------------------------- -As we've seen, view callables needn't always return a Response object. -Instead, they may return an arbitrary Python object, with the expectation +As we've seen, a view callable needn't always return a Response object. +Instead, it may return an arbitrary Python object, with the expectation that a :term:`renderer` will convert that object into a response instance on your behalf. Some renderers use a templating system; other renderers use object serialization techniques. -- cgit v1.2.3 From 6ce39f11b76dc599dfc897eab43bcf236b26c5d5 Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Mon, 22 Apr 2013 22:43:55 +0300 Subject: remove redundant text Also, this fact has already been explained in the chapter, so mention that. --- docs/narr/renderers.rst | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index b4eb95186..bcab0e3f4 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -80,12 +80,10 @@ response attributes (such as headers and the HTTP status code) by attaching a property to the ``request.response`` attribute. See :ref:`request_response_attr`. -If the :term:`view callable` associated with a :term:`view configuration` -returns a Response object directly, any renderer associated with the view -configuration is ignored, and the response is passed back to :app:`Pyramid` -unchanged. For example, if your view callable returns an instance of the -:class:`pyramid.response.Response` class as a response, no renderer -will be employed. +As already mentioned, if the :term:`view callable` associated with a +:term:`view configuration` returns a Response object (or its instance), +any renderer associated with the view configuration is ignored, +and the response is passed back to :app:`Pyramid` unchanged. For example: .. code-block:: python :linenos: -- cgit v1.2.3 From e8f87a048cf7cc4ac8673dd15d5743afa63e2fbb Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Mon, 22 Apr 2013 23:25:12 +0300 Subject: remove redundancy --- docs/narr/renderers.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index b4eb95186..2ebf9b20e 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -140,7 +140,7 @@ used in the ``renderer`` attribute of view configurations. ``string``: String Renderer ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The ``string`` renderer is a renderer which renders a view callable result to +The ``string`` renderer renders a view callable result to a string. If a view callable returns a non-Response object, and the ``string`` renderer is associated in that view's configuration, the result will be to run the object through the Python ``str`` function to generate a -- cgit v1.2.3 From 5028d84aeb6ac79ee7db4dc4012ff4caaba10e77 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Thu, 18 Jul 2013 18:09:20 -0400 Subject: normalize notations used for string and json renderer return values, closes #1005 --- docs/narr/renderers.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 20a9eda31..a2811dbae 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -198,7 +198,7 @@ representing the JSON serialization of the return value: .. code-block:: python - '{"content": "Hello!"}' + {"content": "Hello!"} The return value needn't be a dictionary, but the return value must contain values serializable by the configured serializer (by default ``json.dumps``). -- cgit v1.2.3 From 6ca99b5b42ca13a25a22474c927733d2d16d7cbe Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Wed, 4 Sep 2013 23:32:43 -0500 Subject: remove some mako/chameleon renderer docs --- docs/narr/renderers.rst | 179 ++++++------------------------------------------ 1 file changed, 21 insertions(+), 158 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index a2811dbae..212832474 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -365,136 +365,6 @@ The same custom-object serialization scheme defined used for a "normal" JSON renderer in :ref:`json_serializing_custom_objects` can be used when passing values to a JSONP renderer too. -.. index:: - pair: renderer; chameleon - -.. _chameleon_template_renderers: - -``*.pt`` or ``*.txt``: Chameleon Template Renderers -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Two built-in renderers exist for :term:`Chameleon` templates. - -If the ``renderer`` attribute of a view configuration is an absolute path, a -relative path or :term:`asset specification` which has a final path element -with a filename extension of ``.pt``, the Chameleon ZPT renderer is used. -See :ref:`chameleon_zpt_templates` for more information about ZPT templates. - -If the ``renderer`` attribute of a view configuration is an absolute path or -a :term:`asset specification` which has a final path element with a filename -extension of ``.txt``, the :term:`Chameleon` text renderer is used. See -:ref:`chameleon_text_templates` for more information about Chameleon text -templates. - -The behavior of these renderers is the same, except for the engine -used to render the template. - -When a ``renderer`` attribute that names a template path or :term:`asset -specification` (e.g. ``myproject:templates/foo.pt`` or -``myproject:templates/foo.txt``) is used, the view must return a -:term:`Response` object or a Python *dictionary*. If the view callable with -an associated template returns a Python dictionary, the named template will -be passed the dictionary as its keyword arguments, and the template renderer -implementation will return the resulting rendered template in a response to -the user. If the view callable returns anything but a Response object or a -dictionary, an error will be raised. - -Before passing keywords to the template, the keyword arguments derived from -the dictionary returned by the view are augmented. The callable object -- -whatever object was used to define the view -- will be automatically inserted -into the set of keyword arguments passed to the template as the ``view`` -keyword. If the view callable was a class, the ``view`` keyword will be an -instance of that class. Also inserted into the keywords passed to the -template are ``renderer_name`` (the string used in the ``renderer`` attribute -of the directive), ``renderer_info`` (an object containing renderer-related -information), ``context`` (the context resource of the view used to render -the template), and ``request`` (the request passed to the view used to render -the template). ``request`` is also available as ``req`` in Pyramid 1.3+. - -Here's an example view configuration which uses a Chameleon ZPT renderer: - -.. code-block:: python - :linenos: - - # config is an instance of pyramid.config.Configurator - - config.add_view('myproject.views.hello_world', - name='hello', - context='myproject.resources.Hello', - renderer='myproject:templates/foo.pt') - -Here's an example view configuration which uses a Chameleon text renderer: - -.. code-block:: python - :linenos: - - config.add_view('myproject.views.hello_world', - name='hello', - context='myproject.resources.Hello', - renderer='myproject:templates/foo.txt') - -Views which use a Chameleon renderer can vary response attributes by using -the API of the ``request.response`` attribute. See -:ref:`request_response_attr`. - -.. index:: - pair: renderer; mako - -.. _mako_template_renderers: - -``*.mak`` or ``*.mako``: Mako Template Renderer -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The ``Mako`` template renderer renders views using a Mako template. When -used, the view must return a Response object or a Python *dictionary*. The -dictionary items will then be used in the global template space. If the view -callable returns anything but a Response object or a dictionary, an error -will be raised. - -When using a ``renderer`` argument to a :term:`view configuration` to specify -a Mako template, the value of the ``renderer`` may be a path relative to the -``mako.directories`` setting (e.g. ``some/template.mak``) or, alternately, -it may be a :term:`asset specification` -(e.g. ``apackage:templates/sometemplate.mak``). Mako templates may -internally inherit other Mako templates using a relative filename or a -:term:`asset specification` as desired. - -Here's an example view configuration which uses a relative path: - -.. code-block:: python - :linenos: - - # config is an instance of pyramid.config.Configurator - - config.add_view('myproject.views.hello_world', - name='hello', - context='myproject.resources.Hello', - renderer='foo.mak') - -It's important to note that in Mako's case, the 'relative' path name -``foo.mak`` above is not relative to the package, but is relative to the -directory (or directories) configured for Mako via the ``mako.directories`` -configuration file setting. - -The renderer can also be provided in :term:`asset specification` -format. Here's an example view configuration which uses one: - -.. code-block:: python - :linenos: - - config.add_view('myproject.views.hello_world', - name='hello', - context='myproject.resources.Hello', - renderer='mypackage:templates/foo.mak') - -The above configuration will use the file named ``foo.mak`` in the -``templates`` directory of the ``mypackage`` package. - -The ``Mako`` template renderer can take additional arguments beyond the -standard ``pyramid.reload_templates`` setting, see the -:ref:`environment_chapter` for additional -:ref:`mako_template_renderer_settings`. - .. index:: single: response headers (from a renderer) single: renderer response headers @@ -739,44 +609,37 @@ ending with ``.jinja2`` in its ``renderer`` value. The ``name`` passed to the ``MyJinja2Renderer`` constructor will be the full value that was set as ``renderer=`` in the view configuration. -.. index:: - pair: renderer; changing +Adding a Default Renderer +~~~~~~~~~~~~~~~~~~~~~~~~~ -Changing an Existing Renderer -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can associate more than one filename extension with the same existing -renderer implementation as necessary if you need to use a different file -extension for the same kinds of templates. For example, to associate the -``.zpt`` extension with the Chameleon ZPT renderer factory, use the -:meth:`pyramid.config.Configurator.add_renderer` method: +To associate a *default* renderer with *all* view configurations (even +ones which do not possess a ``renderer`` attribute), pass ``None`` as +the ``name`` attribute to the renderer tag: .. code-block:: python - config.add_renderer('.zpt', 'pyramid.chameleon_zpt.renderer_factory') - -After you do this, :app:`Pyramid` will treat templates ending in both the -``.pt`` and ``.zpt`` filename extensions as Chameleon ZPT templates. - -To change the default mapping in which files with a ``.pt`` extension are -rendered via a Chameleon ZPT page template renderer, use a variation on the -following in your application's startup code: - -.. code-block:: python + config.add_renderer(None, 'mypackage.json_renderer_factory') - config.add_renderer('.pt', 'mypackage.pt_renderer') +.. index:: + pair: renderer; changing -After you do this, the :term:`renderer factory` in -``mypackage.pt_renderer`` will be used to render templates which end -in ``.pt``, replacing the default Chameleon ZPT renderer. +Changing an Existing Renderer +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -To associate a *default* renderer with *all* view configurations (even -ones which do not possess a ``renderer`` attribute), pass ``None`` as -the ``name`` attribute to the renderer tag: +Pyramid supports overriding almost every aspect of its setup through its +:ref:`Conflict Resolution ` mechanism. This +means that in most cases overriding a renderer is as simple as using the +:meth:`pyramid.config.Configurator.add_renderer` method to re-define the +template extension. For example, if we'd like to override the ``json`` +extension to specify a new renderer we could do the following: .. code-block:: python - config.add_renderer(None, 'mypackage.json_renderer_factory') + json_renderer = pyramid.renderers.JSON() + config.add_renderer('json', json_renderer) + +After you do this, any views registered with the ``json`` renderer will use +the new renderer. .. index:: pair: renderer; overriding at runtime -- cgit v1.2.3 From b56a6ee9c0c58992df67cdeb021f69d51bcfd26d Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Wed, 4 Sep 2013 23:36:01 -0500 Subject: change focus from we to you --- docs/narr/renderers.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 212832474..bc96f3d7b 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -630,15 +630,15 @@ Pyramid supports overriding almost every aspect of its setup through its :ref:`Conflict Resolution ` mechanism. This means that in most cases overriding a renderer is as simple as using the :meth:`pyramid.config.Configurator.add_renderer` method to re-define the -template extension. For example, if we'd like to override the ``json`` -extension to specify a new renderer we could do the following: +template extension. For example, if you would like to override the ``.txt`` +extension to specify a new renderer you could do the following: .. code-block:: python json_renderer = pyramid.renderers.JSON() config.add_renderer('json', json_renderer) -After you do this, any views registered with the ``json`` renderer will use +After doing this, any views registered with the ``json`` renderer will use the new renderer. .. index:: -- cgit v1.2.3 From 004d847fe87424f187a920086cb8b9baa8b41b42 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Thu, 5 Sep 2013 00:02:51 -0500 Subject: more chameleon builtin references --- docs/narr/renderers.rst | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index bc96f3d7b..dd67c779c 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -67,9 +67,8 @@ When this configuration is added to an application, the ``myproject.views.my_view`` view callable will now use a ``json`` renderer, which renders view return values to a :term:`JSON` response serialization. -Other built-in renderers include renderers which use the :term:`Chameleon` -templating language to render a dictionary to a response. Additional -renderers can be added by developers to the system as necessary. +Pyramid defines several :ref:`built_in_renderers`, and additional renderers +can be added by developers to the system as necessary. See :ref:`adding_and_overriding_renderers`. Views which use a renderer and return a non-Response value can vary non-body -- cgit v1.2.3 From 6f2d0468856b2a3ca84cb22c379196298b2399ea Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Thu, 5 Sep 2013 00:35:41 -0500 Subject: add a section mentioning external template bindings --- docs/narr/renderers.rst | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index dd67c779c..21c59c06a 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -364,6 +364,31 @@ The same custom-object serialization scheme defined used for a "normal" JSON renderer in :ref:`json_serializing_custom_objects` can be used when passing values to a JSONP renderer too. +Available Add-On Template System Bindings +----------------------------------------- + +The Pylons Project maintains several packages providing bindings to different +templating languages including the following: + ++------------------------------+------------------------------+ +| Template Language | Pyramid Bindings | ++==============================+==============================+ +| Chameleon_ | pyramid_chameleon_ | ++------------------------------+------------------------------+ +| Jinja2_ | pyramid_jinja2_ | ++------------------------------+------------------------------+ +| Mako_ | pyramid_mako_ | ++------------------------------+------------------------------+ + +.. _Chameleon: http://chameleon.readthedocs.org/en/latest/ +.. _pyramid_chameleon: https://pypi.python.org/pypi/pyramid_chameleon + +.. _Jinja2: http://jinja.pocoo.org/docs/ +.. _pyramid_jinja2: https://pypi.python.org/pypi/pyramid_jinja2 + +.. _Mako: http://www.makotemplates.org/ +.. _pyramid_mako: https://pypi.python.org/pypi/pyramid_mako + .. index:: single: response headers (from a renderer) single: renderer response headers -- cgit v1.2.3 From f6f1d1685f09f1ecd3717c90e687a6e3652b4fdc Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Thu, 5 Sep 2013 02:32:41 -0500 Subject: remove the deprecated request.response_* attributes --- docs/narr/renderers.rst | 34 ---------------------------------- 1 file changed, 34 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index a2811dbae..9132606b3 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -556,40 +556,6 @@ For more information on attributes of the request, see the API documentation in :ref:`request_module`. For more information on the API of ``request.response``, see :attr:`pyramid.request.Request.response`. -.. _response_prefixed_attrs: - -Deprecated Mechanism to Vary Attributes of Rendered Responses -------------------------------------------------------------- - -In previous releases of Pyramid (1.0 and before), the ``request.response`` -attribute did not exist. Instead, Pyramid required users to set special -``response_`` -prefixed attributes of the request to influence response -behavior. As of Pyramid 1.1, those request attributes are deprecated and -their use will cause a deprecation warning to be issued when used. Until -their existence is removed completely, we document them below, for benefit of -people with older code bases. - -``response_content_type`` - Defines the content-type of the resulting response, - e.g. ``text/xml``. - -``response_headerlist`` - A sequence of tuples describing header values that should be set in the - response, e.g. ``[('Set-Cookie', 'abc=123'), ('X-My-Header', 'foo')]``. - -``response_status`` - A WSGI-style status code (e.g. ``200 OK``) describing the status of the - response. - -``response_charset`` - The character set (e.g. ``UTF-8``) of the response. - -``response_cache_for`` - A value in seconds which will influence ``Cache-Control`` and ``Expires`` - headers in the returned response. The same can also be achieved by - returning various values in the ``response_headerlist``, this is purely a - convenience. - .. _adding_and_overriding_renderers: Adding and Changing Renderers -- cgit v1.2.3 From bc0a26ac2b75de362a4bf8142b3385788f318f47 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Thu, 5 Sep 2013 02:50:15 -0500 Subject: add index for custom template engines --- docs/narr/renderers.rst | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 21c59c06a..8de3cd29d 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -364,6 +364,14 @@ The same custom-object serialization scheme defined used for a "normal" JSON renderer in :ref:`json_serializing_custom_objects` can be used when passing values to a JSONP renderer too. +.. index:: + single: template system bindings + single: Chameleon + single: Jinja2 + single: Mako + +.. _available_template_system_bindings: + Available Add-On Template System Bindings ----------------------------------------- -- cgit v1.2.3 From b9ce00bee0b6f1f5b0174960f2087a418c1488a7 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Thu, 5 Sep 2013 22:57:46 -0500 Subject: move templating bindings back into the templating chapter --- docs/narr/renderers.rst | 38 +++++--------------------------------- 1 file changed, 5 insertions(+), 33 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 8de3cd29d..8afc9c4ab 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -128,6 +128,11 @@ Built-In Renderers Several built-in renderers exist in :app:`Pyramid`. These renderers can be used in the ``renderer`` attribute of view configurations. +.. note:: + + Bindings for officially supported templating languages can be found + at :ref:`available_template_system_bindings`. + .. index:: pair: renderer; string @@ -364,39 +369,6 @@ The same custom-object serialization scheme defined used for a "normal" JSON renderer in :ref:`json_serializing_custom_objects` can be used when passing values to a JSONP renderer too. -.. index:: - single: template system bindings - single: Chameleon - single: Jinja2 - single: Mako - -.. _available_template_system_bindings: - -Available Add-On Template System Bindings ------------------------------------------ - -The Pylons Project maintains several packages providing bindings to different -templating languages including the following: - -+------------------------------+------------------------------+ -| Template Language | Pyramid Bindings | -+==============================+==============================+ -| Chameleon_ | pyramid_chameleon_ | -+------------------------------+------------------------------+ -| Jinja2_ | pyramid_jinja2_ | -+------------------------------+------------------------------+ -| Mako_ | pyramid_mako_ | -+------------------------------+------------------------------+ - -.. _Chameleon: http://chameleon.readthedocs.org/en/latest/ -.. _pyramid_chameleon: https://pypi.python.org/pypi/pyramid_chameleon - -.. _Jinja2: http://jinja.pocoo.org/docs/ -.. _pyramid_jinja2: https://pypi.python.org/pypi/pyramid_jinja2 - -.. _Mako: http://www.makotemplates.org/ -.. _pyramid_mako: https://pypi.python.org/pypi/pyramid_mako - .. index:: single: response headers (from a renderer) single: renderer response headers -- cgit v1.2.3 From db1efe21c3d9b025883b3ed9b0b897cc3d718c28 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Wed, 11 Sep 2013 18:10:18 -0400 Subject: appease --- docs/narr/renderers.rst | 51 ++++++++++++++++++++++++++++++------------------- 1 file changed, 31 insertions(+), 20 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index e13e09af3..3059aef35 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -207,13 +207,7 @@ representing the JSON serialization of the return value: The return value needn't be a dictionary, but the return value must contain values serializable by the configured serializer (by default ``json.dumps``). -.. note:: - - Extra arguments can be passed to the serializer by overriding the default - ``json`` renderer. See :class:`pyramid.renderers.JSON` and - :ref:`adding_and_overriding_renderers` for more information. - -You can configure a view to use the JSON renderer by naming ``json`` as the +You can configure a view to use the JSON renderer by naming``json`` as the ``renderer`` argument of a view configuration, e.g. by using :meth:`~pyramid.config.Configurator.add_view`: @@ -234,6 +228,18 @@ using the api of the ``request.response`` attribute. See Serializing Custom Objects ++++++++++++++++++++++++++ +Some objects are not, by default, JSON-serializable (such as datetimes and +other arbitrary Python objects). You can, however, register code that makes +non-serializable objects serializable in two ways: + +- By defining a ``__json__`` method on objects in your application. + +- For objects you don't "own", you can register JSON renderer that knows about + an *adapter* for that kind of object. + +Using a Custom ``__json__`` Method +********************************** + Custom objects can be made easily JSON-serializable in Pyramid by defining a ``__json__`` method on the object's class. This method should return values natively JSON-serializable (such as ints, lists, dictionaries, strings, and @@ -259,6 +265,9 @@ will be the active request object at render time. # the JSON value returned by ``objects`` will be: # [{"x": 1}, {"x": 2}] +Using the ``add_adapter`` Method of a Custom JSON Renderer +********************************************************** + If you aren't the author of the objects being serialized, it won't be possible (or at least not reasonable) to add a custom ``__json__`` method to their classes in order to influence serialization. If the object passed @@ -273,19 +282,21 @@ objects using the registered adapters. A short example follows: from pyramid.renderers import JSON - json_renderer = JSON() - def datetime_adapter(obj, request): - return obj.isoformat() - json_renderer.add_adapter(datetime.datetime, datetime_adapter) - - # then during configuration .... - config = Configurator() - config.add_renderer('json', json_renderer) - -The adapter should accept two arguments: the object needing to be serialized -and ``request``, which will be the current request object at render time. -The adapter should raise a :exc:`TypeError` if it can't determine what to do -with the object. + if __name__ == '__main__': + config = Configurator() + json_renderer = JSON() + def datetime_adapter(obj, request): + return obj.isoformat() + json_renderer.add_adapter(datetime.datetime, datetime_adapter) + config.add_renderer('json', json_renderer) + +The ``add_adapter`` method should accept two arguments: the *class* of the object that you want this adapter to run for (in the example above, +``datetime.datetime``), and the adapter itself. + +The adapter should be a callable. It should accept two arguments: the object +needing to be serialized and ``request``, which will be the current request +object at render time. The adapter should raise a :exc:`TypeError` +if it can't determine what to do with the object. See :class:`pyramid.renderers.JSON` and :ref:`adding_and_overriding_renderers` for more information. -- cgit v1.2.3 From 68d16988404aec339fde1df7822c783d3ea23af6 Mon Sep 17 00:00:00 2001 From: "Karl O. Pinc" Date: Wed, 2 Oct 2013 11:35:34 -0500 Subject: Docs: renderers.rst: Explain typical renderer usage. --- docs/narr/renderers.rst | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 3059aef35..235dbaf83 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -49,10 +49,14 @@ Writing View Callables Which Use a Renderer ------------------------------------------- As we've seen, a view callable needn't always return a Response object. -Instead, it may return an arbitrary Python object, with the expectation -that a :term:`renderer` will convert that object into a response instance on -your behalf. Some renderers use a templating system; other renderers use -object serialization techniques. +Instead, it may return an arbitrary Python object, with the expectation that +a :term:`renderer` will convert that object into a response instance on your +behalf. Some renderers use a templating system; other renderers use object +serialization techniques. Because renderers inject variable data into some +output (otherwise a static Response object could be returned) the renderer +must have some means of identifying the data and mapping its transformation +into the desired output. Often, as the means of providing this mapping, the +object supplied to the renderer is a Python dictionary. View configuration can vary the renderer associated with a view callable via the ``renderer`` attribute. For example, this call to -- cgit v1.2.3 From 5bf27497638ad607f0e42feb10145cd6720b74d3 Mon Sep 17 00:00:00 2001 From: "Karl O. Pinc" Date: Wed, 2 Oct 2013 15:20:59 -0500 Subject: Docs: Make statements more concreate regards renderers getting data from dictionaries. --- docs/narr/renderers.rst | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 235dbaf83..4046c67fa 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -52,11 +52,9 @@ As we've seen, a view callable needn't always return a Response object. Instead, it may return an arbitrary Python object, with the expectation that a :term:`renderer` will convert that object into a response instance on your behalf. Some renderers use a templating system; other renderers use object -serialization techniques. Because renderers inject variable data into some -output (otherwise a static Response object could be returned) the renderer -must have some means of identifying the data and mapping its transformation -into the desired output. Often, as the means of providing this mapping, the -object supplied to the renderer is a Python dictionary. +serialization techniques. In practice, renderers obtain application data +values from Python dictionaries so, in practice, view callables which use +renderers return Python dictionaries. View configuration can vary the renderer associated with a view callable via the ``renderer`` attribute. For example, this call to -- cgit v1.2.3 From 1f7a00346411033d935bf931c206b585353f8be4 Mon Sep 17 00:00:00 2001 From: "Karl O. Pinc" Date: Sat, 5 Oct 2013 00:37:09 -0500 Subject: Docs: Link from renderer narrative docs to example render_to_response call, and index the example. More fully explain the 2 examples, one with render_to_response call and one without. --- docs/narr/renderers.rst | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 4046c67fa..b86f7298b 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -56,10 +56,12 @@ serialization techniques. In practice, renderers obtain application data values from Python dictionaries so, in practice, view callables which use renderers return Python dictionaries. -View configuration can vary the renderer associated with a view callable via -the ``renderer`` attribute. For example, this call to -:meth:`~pyramid.config.Configurator.add_view` associates the ``json`` renderer -with a view callable: +View callables can :ref:`explicitly call +` renderers but, typically, view +configuration declares the renderer used to render a view callable's +results. This is done with the ``renderer`` attribute. For example, +this call to :meth:`~pyramid.config.Configurator.add_view` associates +the ``json`` renderer with a view callable: .. code-block:: python -- cgit v1.2.3 From 70b05dfaea547fea328a7054acd921f02be34a87 Mon Sep 17 00:00:00 2001 From: "Karl O. Pinc" Date: Mon, 7 Oct 2013 16:06:15 -0500 Subject: Docs: renders.rst: Use punctuation to make sentence simpler. --- docs/narr/renderers.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index b86f7298b..49f834ecb 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -57,7 +57,7 @@ values from Python dictionaries so, in practice, view callables which use renderers return Python dictionaries. View callables can :ref:`explicitly call -` renderers but, typically, view +` renderers; but typically view configuration declares the renderer used to render a view callable's results. This is done with the ``renderer`` attribute. For example, this call to :meth:`~pyramid.config.Configurator.add_view` associates -- cgit v1.2.3 From 77497acef17d5e5996ac231bf8ac9b679b291316 Mon Sep 17 00:00:00 2001 From: "Karl O. Pinc" Date: Mon, 7 Oct 2013 16:10:18 -0500 Subject: Docs: renders.rst: Break sentence into two to simplify. --- docs/narr/renderers.rst | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 49f834ecb..b542e42a2 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -57,11 +57,12 @@ values from Python dictionaries so, in practice, view callables which use renderers return Python dictionaries. View callables can :ref:`explicitly call -` renderers; but typically view -configuration declares the renderer used to render a view callable's -results. This is done with the ``renderer`` attribute. For example, -this call to :meth:`~pyramid.config.Configurator.add_view` associates -the ``json`` renderer with a view callable: +` renderers, but they typically +don't. Instead view configuration declares the renderer used to +render a view callable's results. This is done with the ``renderer`` +attribute. For example, this call to +:meth:`~pyramid.config.Configurator.add_view` associates the ``json`` +renderer with a view callable: .. code-block:: python -- cgit v1.2.3 From 0681d5798574d5f3ed644bf56086208c8571e0b9 Mon Sep 17 00:00:00 2001 From: "Karl O. Pinc" Date: Mon, 7 Oct 2013 16:12:27 -0500 Subject: Docs: renders.rst: Make sentences short per IRC chat with committers. --- docs/narr/renderers.rst | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index b542e42a2..7c25386f5 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -56,13 +56,11 @@ serialization techniques. In practice, renderers obtain application data values from Python dictionaries so, in practice, view callables which use renderers return Python dictionaries. -View callables can :ref:`explicitly call -` renderers, but they typically -don't. Instead view configuration declares the renderer used to -render a view callable's results. This is done with the ``renderer`` -attribute. For example, this call to -:meth:`~pyramid.config.Configurator.add_view` associates the ``json`` -renderer with a view callable: +View callables can :ref:`explicitly call ` +renderers. Typically view configuration declares the renderer used to render +a view callable's results. This is done with the ``renderer`` attribute. +For example, this call to :meth:`~pyramid.config.Configurator.add_view` +associates the ``json`` renderer with a view callable: .. code-block:: python -- cgit v1.2.3 From a26d09f291bdf4f9c7853b1dbfc9643a678a7b94 Mon Sep 17 00:00:00 2001 From: "Karl O. Pinc" Date: Mon, 7 Oct 2013 16:29:31 -0500 Subject: Docs: renders.rst: Make sentences that everybody's happy with. --- docs/narr/renderers.rst | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 7c25386f5..740c81555 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -57,10 +57,11 @@ values from Python dictionaries so, in practice, view callables which use renderers return Python dictionaries. View callables can :ref:`explicitly call ` -renderers. Typically view configuration declares the renderer used to render -a view callable's results. This is done with the ``renderer`` attribute. -For example, this call to :meth:`~pyramid.config.Configurator.add_view` -associates the ``json`` renderer with a view callable: +renderers, but typically don't. Instead view configuration declares the +renderer used to render a view callable's results. This is done with the +``renderer`` attribute. For example, this call to +:meth:`~pyramid.config.Configurator.add_view` associates the ``json`` +renderer with a view callable: .. code-block:: python -- cgit v1.2.3 From 777112d521e337fefc2e0c217add7ac283d087b3 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Sat, 19 Oct 2013 03:48:01 -0500 Subject: link to the public renderer interfaces --- docs/narr/renderers.rst | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 740c81555..4f8c4bf77 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -480,8 +480,11 @@ Adding a New Renderer You may add a new renderer by creating and registering a :term:`renderer factory`. -A renderer factory implementation is typically a class with the -following interface: +A renderer factory implementation should conform to the +:class:`pyramid.interfaces.IRendererFactory` interface. It should be capable +of creating an object that conforms to the +:class:`pyramid.interfaces.IRenderer` interface. A typical class that follows +this setup is as follows: .. code-block:: python :linenos: -- cgit v1.2.3 From 3c966ca70dc1259a1a524ff524a4120011b2fcc1 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Sat, 10 Oct 2015 00:52:07 -0700 Subject: minor grammar, wrap 79 cols --- docs/narr/renderers.rst | 321 +++++++++++++++++++++++------------------------- 1 file changed, 156 insertions(+), 165 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index 4f8c4bf77..cc5baf05e 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -5,8 +5,8 @@ Renderers A view callable needn't *always* return a :term:`Response` object. If a view happens to return something which does not implement the Pyramid Response -interface, :app:`Pyramid` will attempt to use a :term:`renderer` to construct -a response. For example: +interface, :app:`Pyramid` will attempt to use a :term:`renderer` to construct a +response. For example: .. code-block:: python :linenos: @@ -17,27 +17,26 @@ a response. For example: def hello_world(request): return {'content':'Hello!'} -The above example returns a *dictionary* from the view callable. A -dictionary does not implement the Pyramid response interface, so you might -believe that this example would fail. However, since a ``renderer`` is -associated with the view callable through its :term:`view configuration` (in -this case, using a ``renderer`` argument passed to -:func:`~pyramid.view.view_config`), if the view does *not* return a Response -object, the renderer will attempt to convert the result of the view to a -response on the developer's behalf. +The above example returns a *dictionary* from the view callable. A dictionary +does not implement the Pyramid response interface, so you might believe that +this example would fail. However, since a ``renderer`` is associated with the +view callable through its :term:`view configuration` (in this case, using a +``renderer`` argument passed to :func:`~pyramid.view.view_config`), if the view +does *not* return a Response object, the renderer will attempt to convert the +result of the view to a response on the developer's behalf. -Of course, if no renderer is associated with a view's configuration, -returning anything except an object which implements the Response interface -will result in an error. And, if a renderer *is* used, whatever is returned -by the view must be compatible with the particular kind of renderer used, or -an error may occur during view invocation. +Of course, if no renderer is associated with a view's configuration, returning +anything except an object which implements the Response interface will result +in an error. And, if a renderer *is* used, whatever is returned by the view +must be compatible with the particular kind of renderer used, or an error may +occur during view invocation. -One exception exists: it is *always* OK to return a Response object, even -when a ``renderer`` is configured. In such cases, the renderer is -bypassed entirely. +One exception exists: it is *always* OK to return a Response object, even when +a ``renderer`` is configured. In such cases, the renderer is bypassed +entirely. -Various types of renderers exist, including serialization renderers -and renderers which use templating systems. +Various types of renderers exist, including serialization renderers and +renderers which use templating systems. .. index:: single: renderer @@ -49,19 +48,19 @@ Writing View Callables Which Use a Renderer ------------------------------------------- As we've seen, a view callable needn't always return a Response object. -Instead, it may return an arbitrary Python object, with the expectation that -a :term:`renderer` will convert that object into a response instance on your -behalf. Some renderers use a templating system; other renderers use object -serialization techniques. In practice, renderers obtain application data -values from Python dictionaries so, in practice, view callables which use +Instead, it may return an arbitrary Python object, with the expectation that a +:term:`renderer` will convert that object into a response instance on your +behalf. Some renderers use a templating system, while other renderers use +object serialization techniques. In practice, renderers obtain application +data values from Python dictionaries so, in practice, view callables which use renderers return Python dictionaries. View callables can :ref:`explicitly call ` renderers, but typically don't. Instead view configuration declares the renderer used to render a view callable's results. This is done with the ``renderer`` attribute. For example, this call to -:meth:`~pyramid.config.Configurator.add_view` associates the ``json`` -renderer with a view callable: +:meth:`~pyramid.config.Configurator.add_view` associates the ``json`` renderer +with a view callable: .. code-block:: python @@ -71,19 +70,19 @@ When this configuration is added to an application, the ``myproject.views.my_view`` view callable will now use a ``json`` renderer, which renders view return values to a :term:`JSON` response serialization. -Pyramid defines several :ref:`built_in_renderers`, and additional renderers -can be added by developers to the system as necessary. -See :ref:`adding_and_overriding_renderers`. +Pyramid defines several :ref:`built_in_renderers`, and additional renderers can +be added by developers to the system as necessary. See +:ref:`adding_and_overriding_renderers`. Views which use a renderer and return a non-Response value can vary non-body response attributes (such as headers and the HTTP status code) by attaching a -property to the ``request.response`` attribute. -See :ref:`request_response_attr`. +property to the ``request.response`` attribute. See +:ref:`request_response_attr`. As already mentioned, if the :term:`view callable` associated with a -:term:`view configuration` returns a Response object (or its instance), -any renderer associated with the view configuration is ignored, -and the response is passed back to :app:`Pyramid` unchanged. For example: +:term:`view configuration` returns a Response object (or its instance), any +renderer associated with the view configuration is ignored, and the response is +passed back to :app:`Pyramid` unchanged. For example: .. code-block:: python :linenos: @@ -126,7 +125,7 @@ avoid rendering: .. _built_in_renderers: -Built-In Renderers +Built-in Renderers ------------------ Several built-in renderers exist in :app:`Pyramid`. These renderers can be @@ -134,8 +133,8 @@ used in the ``renderer`` attribute of view configurations. .. note:: - Bindings for officially supported templating languages can be found - at :ref:`available_template_system_bindings`. + Bindings for officially supported templating languages can be found at + :ref:`available_template_system_bindings`. .. index:: pair: renderer; string @@ -143,17 +142,15 @@ used in the ``renderer`` attribute of view configurations. ``string``: String Renderer ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The ``string`` renderer renders a view callable result to -a string. If a view callable returns a non-Response object, and the -``string`` renderer is associated in that view's configuration, the result -will be to run the object through the Python ``str`` function to generate a -string. Note that if a Unicode object is returned by the view callable, it -is not ``str()`` -ified. +The ``string`` renderer renders a view callable result to a string. If a view +callable returns a non-Response object, and the ``string`` renderer is +associated in that view's configuration, the result will be to run the object +through the Python ``str`` function to generate a string. Note that if a +Unicode object is returned by the view callable, it is not ``str()``-ified. Here's an example of a view that returns a dictionary. If the ``string`` -renderer is specified in the configuration for this view, the view will -render the returned dictionary to the ``str()`` representation of the -dictionary: +renderer is specified in the configuration for this view, the view will render +the returned dictionary to the ``str()`` representation of the dictionary: .. code-block:: python :linenos: @@ -164,8 +161,8 @@ dictionary: def hello_world(request): return {'content':'Hello!'} -The body of the response returned by such a view will be a string -representing the ``str()`` serialization of the return value: +The body of the response returned by such a view will be a string representing +the ``str()`` serialization of the return value: .. code-block:: python @@ -184,13 +181,13 @@ JSON Renderer ~~~~~~~~~~~~~ The ``json`` renderer renders view callable results to :term:`JSON`. By -default, it passes the return value through the ``json.dumps`` standard -library function, and wraps the result in a response object. It also sets -the response content-type to ``application/json``. +default, it passes the return value through the ``json.dumps`` standard library +function, and wraps the result in a response object. It also sets the response +content-type to ``application/json``. Here's an example of a view that returns a dictionary. Since the ``json`` -renderer is specified in the configuration for this view, the view will -render the returned dictionary to a JSON serialization: +renderer is specified in the configuration for this view, the view will render +the returned dictionary to a JSON serialization: .. code-block:: python :linenos: @@ -201,8 +198,8 @@ render the returned dictionary to a JSON serialization: def hello_world(request): return {'content':'Hello!'} -The body of the response returned by such a view will be a string -representing the JSON serialization of the return value: +The body of the response returned by such a view will be a string representing +the JSON serialization of the return value: .. code-block:: python @@ -211,8 +208,8 @@ representing the JSON serialization of the return value: The return value needn't be a dictionary, but the return value must contain values serializable by the configured serializer (by default ``json.dumps``). -You can configure a view to use the JSON renderer by naming``json`` as the -``renderer`` argument of a view configuration, e.g. by using +You can configure a view to use the JSON renderer by naming ``json`` as the +``renderer`` argument of a view configuration, e.g., by using :meth:`~pyramid.config.Configurator.add_view`: .. code-block:: python @@ -224,7 +221,7 @@ You can configure a view to use the JSON renderer by naming``json`` as the renderer='json') Views which use the JSON renderer can vary non-body response attributes by -using the api of the ``request.response`` attribute. See +using the API of the ``request.response`` attribute. See :ref:`request_response_attr`. .. _json_serializing_custom_objects: @@ -232,23 +229,23 @@ using the api of the ``request.response`` attribute. See Serializing Custom Objects ++++++++++++++++++++++++++ -Some objects are not, by default, JSON-serializable (such as datetimes and -other arbitrary Python objects). You can, however, register code that makes +Some objects are not, by default, JSON-serializable (such as datetimes and +other arbitrary Python objects). You can, however, register code that makes non-serializable objects serializable in two ways: -- By defining a ``__json__`` method on objects in your application. +- Define a ``__json__`` method on objects in your application. -- For objects you don't "own", you can register JSON renderer that knows about - an *adapter* for that kind of object. +- For objects you don't "own", you can register a JSON renderer that knows + about an *adapter* for that kind of object. Using a Custom ``__json__`` Method ********************************** Custom objects can be made easily JSON-serializable in Pyramid by defining a ``__json__`` method on the object's class. This method should return values -natively JSON-serializable (such as ints, lists, dictionaries, strings, and -so forth). It should accept a single additional argument, ``request``, which -will be the active request object at render time. +natively JSON-serializable (such as ints, lists, dictionaries, strings, and so +forth). It should accept a single additional argument, ``request``, which will +be the active request object at render time. .. code-block:: python :linenos: @@ -272,14 +269,14 @@ will be the active request object at render time. Using the ``add_adapter`` Method of a Custom JSON Renderer ********************************************************** -If you aren't the author of the objects being serialized, it won't be -possible (or at least not reasonable) to add a custom ``__json__`` method -to their classes in order to influence serialization. If the object passed -to the renderer is not a serializable type, and has no ``__json__`` method, -usually a :exc:`TypeError` will be raised during serialization. You can -change this behavior by creating a custom JSON renderer and adding adapters -to handle custom types. The renderer will attempt to adapt non-serializable -objects using the registered adapters. A short example follows: +If you aren't the author of the objects being serialized, it won't be possible +(or at least not reasonable) to add a custom ``__json__`` method to their +classes in order to influence serialization. If the object passed to the +renderer is not a serializable type and has no ``__json__`` method, usually a +:exc:`TypeError` will be raised during serialization. You can change this +behavior by creating a custom JSON renderer and adding adapters to handle +custom types. The renderer will attempt to adapt non-serializable objects using +the registered adapters. A short example follows: .. code-block:: python :linenos: @@ -294,16 +291,17 @@ objects using the registered adapters. A short example follows: json_renderer.add_adapter(datetime.datetime, datetime_adapter) config.add_renderer('json', json_renderer) -The ``add_adapter`` method should accept two arguments: the *class* of the object that you want this adapter to run for (in the example above, +The ``add_adapter`` method should accept two arguments: the *class* of the +object that you want this adapter to run for (in the example above, ``datetime.datetime``), and the adapter itself. -The adapter should be a callable. It should accept two arguments: the object -needing to be serialized and ``request``, which will be the current request -object at render time. The adapter should raise a :exc:`TypeError` -if it can't determine what to do with the object. +The adapter should be a callable. It should accept two arguments: the object +needing to be serialized and ``request``, which will be the current request +object at render time. The adapter should raise a :exc:`TypeError` if it can't +determine what to do with the object. -See :class:`pyramid.renderers.JSON` and -:ref:`adding_and_overriding_renderers` for more information. +See :class:`pyramid.renderers.JSON` and :ref:`adding_and_overriding_renderers` +for more information. .. versionadded:: 1.4 Serializing custom objects. @@ -319,12 +317,12 @@ JSONP Renderer .. versionadded:: 1.1 :class:`pyramid.renderers.JSONP` is a `JSONP -`_ renderer factory helper which -implements a hybrid json/jsonp renderer. JSONP is useful for making -cross-domain AJAX requests. +`_ renderer factory helper which implements +a hybrid JSON/JSONP renderer. JSONP is useful for making cross-domain AJAX +requests. -Unlike other renderers, a JSONP renderer needs to be configured at startup -time "by hand". Configure a JSONP renderer using the +Unlike other renderers, a JSONP renderer needs to be configured at startup time +"by hand". Configure a JSONP renderer using the :meth:`pyramid.config.Configurator.add_renderer` method: .. code-block:: python @@ -355,8 +353,8 @@ When a view is called that uses a JSONP renderer: renderer (by default, ``callback``), the renderer will return a JSONP response. -- If there is no callback parameter in the request's query string, the - renderer will return a 'plain' JSON response. +- If there is no callback parameter in the request's query string, the renderer + will return a "plain" JSON response. Javscript library AJAX functionality will help you make JSONP requests. For example, JQuery has a `getJSON function @@ -364,7 +362,7 @@ For example, JQuery has a `getJSON function complicated) functionality in its `ajax function `_. -For example (Javascript): +For example (JavaScript): .. code-block:: javascript @@ -375,10 +373,9 @@ For example (Javascript): '&callback=?'; jqhxr = $.getJSON(api_url); -The string ``callback=?`` above in the ``url`` param to the JQuery -``getJSON`` function indicates to jQuery that the query should be made as -a JSONP request; the ``callback`` parameter will be automatically filled -in for you and used. +The string ``callback=?`` above in the ``url`` param to the JQuery ``getJSON`` +function indicates to jQuery that the query should be made as a JSONP request; +the ``callback`` parameter will be automatically filled in for you and used. The same custom-object serialization scheme defined used for a "normal" JSON renderer in :ref:`json_serializing_custom_objects` can be used when passing @@ -397,10 +394,9 @@ Before a response constructed by a :term:`renderer` is returned to :app:`Pyramid`, several attributes of the request are examined which have the potential to influence response behavior. -View callables that don't directly return a response should use the API of -the :class:`pyramid.response.Response` attribute available as -``request.response`` during their execution, to influence associated response -behavior. +View callables that don't directly return a response should use the API of the +:class:`pyramid.response.Response` attribute, available as ``request.response`` +during their execution, to influence associated response behavior. For example, if you need to change the response status from within a view callable that uses a renderer, assign the ``status`` attribute to the @@ -419,7 +415,7 @@ callable that uses a renderer, assign the ``status`` attribute to the Note that mutations of ``request.response`` in views which return a Response object directly will have no effect unless the response object returned *is* ``request.response``. For example, the following example calls -``request.response.set_cookie``, but this call will have no effect, because a +``request.response.set_cookie``, but this call will have no effect because a different Response object is returned. .. code-block:: python @@ -441,8 +437,8 @@ effect, you must return ``request.response``: request.response.set_cookie('abc', '123') return request.response -For more information on attributes of the request, see the API documentation -in :ref:`request_module`. For more information on the API of +For more information on attributes of the request, see the API documentation in +:ref:`request_module`. For more information on the API of ``request.response``, see :attr:`pyramid.request.Request.response`. .. _adding_and_overriding_renderers: @@ -481,10 +477,9 @@ You may add a new renderer by creating and registering a :term:`renderer factory`. A renderer factory implementation should conform to the -:class:`pyramid.interfaces.IRendererFactory` interface. It should be capable -of creating an object that conforms to the -:class:`pyramid.interfaces.IRenderer` interface. A typical class that follows -this setup is as follows: +:class:`pyramid.interfaces.IRendererFactory` interface. It should be capable of +creating an object that conforms to the :class:`pyramid.interfaces.IRenderer` +interface. A typical class that follows this setup is as follows: .. code-block:: python :linenos: @@ -504,38 +499,36 @@ this setup is as follows: the result (a string or unicode object). The value is the return value of a view. The system value is a dictionary containing available system values - (e.g. view, context, and request). """ + (e.g., view, context, and request). """ The formal interface definition of the ``info`` object passed to a renderer factory constructor is available as :class:`pyramid.interfaces.IRendererInfo`. There are essentially two different kinds of renderer factories: -- A renderer factory which expects to accept an :term:`asset - specification`, or an absolute path, as the ``name`` attribute of the - ``info`` object fed to its constructor. These renderer factories are - registered with a ``name`` value that begins with a dot (``.``). These - types of renderer factories usually relate to a file on the filesystem, - such as a template. +- A renderer factory which expects to accept an :term:`asset specification`, or + an absolute path, as the ``name`` attribute of the ``info`` object fed to its + constructor. These renderer factories are registered with a ``name`` value + that begins with a dot (``.``). These types of renderer factories usually + relate to a file on the filesystem, such as a template. -- A renderer factory which expects to accept a token that does not represent - a filesystem path or an asset specification in the ``name`` - attribute of the ``info`` object fed to its constructor. These renderer - factories are registered with a ``name`` value that does not begin with a - dot. These renderer factories are typically object serializers. +- A renderer factory which expects to accept a token that does not represent a + filesystem path or an asset specification in the ``name`` attribute of the + ``info`` object fed to its constructor. These renderer factories are + registered with a ``name`` value that does not begin with a dot. These + renderer factories are typically object serializers. .. sidebar:: Asset Specifications - An asset specification is a colon-delimited identifier for an - :term:`asset`. The colon separates a Python :term:`package` - name from a package subpath. For example, the asset - specification ``my.package:static/baz.css`` identifies the file named - ``baz.css`` in the ``static`` subdirectory of the ``my.package`` Python - :term:`package`. + An asset specification is a colon-delimited identifier for an :term:`asset`. + The colon separates a Python :term:`package` name from a package subpath. + For example, the asset specification ``my.package:static/baz.css`` + identifies the file named ``baz.css`` in the ``static`` subdirectory of the + ``my.package`` Python :term:`package`. Here's an example of the registration of a simple renderer factory via -:meth:`~pyramid.config.Configurator.add_renderer`, where ``config`` -is an instance of :meth:`pyramid.config.Configurator`: +:meth:`~pyramid.config.Configurator.add_renderer`, where ``config`` is an +instance of :meth:`pyramid.config.Configurator`: .. code-block:: python @@ -556,16 +549,15 @@ renderer by specifying ``amf`` in the ``renderer`` attribute of a def myview(request): return {'Hello':'world'} -At startup time, when a :term:`view configuration` is encountered, which -has a ``name`` attribute that does not contain a dot, the full ``name`` -value is used to construct a renderer from the associated renderer -factory. In this case, the view configuration will create an instance -of an ``MyAMFRenderer`` for each view configuration which includes ``amf`` -as its renderer value. The ``name`` passed to the ``MyAMFRenderer`` -constructor will always be ``amf``. +At startup time, when a :term:`view configuration` is encountered which has a +``name`` attribute that does not contain a dot, the full ``name`` value is used +to construct a renderer from the associated renderer factory. In this case, +the view configuration will create an instance of an ``MyAMFRenderer`` for each +view configuration which includes ``amf`` as its renderer value. The ``name`` +passed to the ``MyAMFRenderer`` constructor will always be ``amf``. -Here's an example of the registration of a more complicated renderer -factory, which expects to be passed a filesystem path: +Here's an example of the registration of a more complicated renderer factory, +which expects to be passed a filesystem path: .. code-block:: python @@ -585,24 +577,23 @@ the ``renderer`` attribute of a :term:`view configuration`: def myview(request): return {'Hello':'world'} -When a :term:`view configuration` is encountered at startup time, which -has a ``name`` attribute that does contain a dot, the value of the name -attribute is split on its final dot. The second element of the split is -typically the filename extension. This extension is used to look up a -renderer factory for the configured view. Then the value of -``renderer`` is passed to the factory to create a renderer for the view. -In this case, the view configuration will create an instance of a -``MyJinja2Renderer`` for each view configuration which includes anything -ending with ``.jinja2`` in its ``renderer`` value. The ``name`` passed -to the ``MyJinja2Renderer`` constructor will be the full value that was -set as ``renderer=`` in the view configuration. +When a :term:`view configuration` is encountered at startup time which has a +``name`` attribute that does contain a dot, the value of the name attribute is +split on its final dot. The second element of the split is typically the +filename extension. This extension is used to look up a renderer factory for +the configured view. Then the value of ``renderer`` is passed to the factory +to create a renderer for the view. In this case, the view configuration will +create an instance of a ``MyJinja2Renderer`` for each view configuration which +includes anything ending with ``.jinja2`` in its ``renderer`` value. The +``name`` passed to the ``MyJinja2Renderer`` constructor will be the full value +that was set as ``renderer=`` in the view configuration. Adding a Default Renderer ~~~~~~~~~~~~~~~~~~~~~~~~~ -To associate a *default* renderer with *all* view configurations (even -ones which do not possess a ``renderer`` attribute), pass ``None`` as -the ``name`` attribute to the renderer tag: +To associate a *default* renderer with *all* view configurations (even ones +which do not possess a ``renderer`` attribute), pass ``None`` as the ``name`` +attribute to the renderer tag: .. code-block:: python @@ -616,40 +607,40 @@ Changing an Existing Renderer Pyramid supports overriding almost every aspect of its setup through its :ref:`Conflict Resolution ` mechanism. This -means that in most cases overriding a renderer is as simple as using the -:meth:`pyramid.config.Configurator.add_renderer` method to re-define the +means that, in most cases, overriding a renderer is as simple as using the +:meth:`pyramid.config.Configurator.add_renderer` method to redefine the template extension. For example, if you would like to override the ``.txt`` -extension to specify a new renderer you could do the following: +extension to specify a new renderer, you could do the following: .. code-block:: python json_renderer = pyramid.renderers.JSON() config.add_renderer('json', json_renderer) -After doing this, any views registered with the ``json`` renderer will use -the new renderer. +After doing this, any views registered with the ``json`` renderer will use the +new renderer. .. index:: pair: renderer; overriding at runtime -Overriding A Renderer At Runtime +Overriding a Renderer at Runtime -------------------------------- .. warning:: This is an advanced feature, not typically used by "civilians". In some circumstances, it is necessary to instruct the system to ignore the static renderer declaration provided by the developer in view configuration, -replacing the renderer with another *after a request starts*. For example, -an "omnipresent" XML-RPC implementation that detects that the request is from -an XML-RPC client might override a view configuration statement made by the -user instructing the view to use a template renderer with one that uses an -XML-RPC renderer. This renderer would produce an XML-RPC representation of -the data returned by an arbitrary view callable. +replacing the renderer with another *after a request starts*. For example, an +"omnipresent" XML-RPC implementation that detects that the request is from an +XML-RPC client might override a view configuration statement made by the user +instructing the view to use a template renderer with one that uses an XML-RPC +renderer. This renderer would produce an XML-RPC representation of the data +returned by an arbitrary view callable. To use this feature, create a :class:`~pyramid.events.NewRequest` :term:`subscriber` which sniffs at the request data and which conditionally -sets an ``override_renderer`` attribute on the request itself, which is the -*name* of a registered renderer. For example: +sets an ``override_renderer`` attribute on the request itself, which in turn is +the *name* of a registered renderer. For example: .. code-block:: python :linenos: @@ -670,6 +661,6 @@ sets an ``override_renderer`` attribute on the request itself, which is the request.override_renderer = 'xmlrpc' return True -The result of such a subscriber will be to replace any existing static -renderer configured by the developer with a (notional, nonexistent) XML-RPC -renderer if the request appears to come from an XML-RPC client. +The result of such a subscriber will be to replace any existing static renderer +configured by the developer with a (notional, nonexistent) XML-RPC renderer, if +the request appears to come from an XML-RPC client. -- cgit v1.2.3 From 8bafd90d6143230391723e1a079f7914af2381ed Mon Sep 17 00:00:00 2001 From: Julien Cigar Date: Mon, 26 Oct 2015 23:55:45 +0100 Subject: .txt -> json --- docs/narr/renderers.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/narr/renderers.rst') diff --git a/docs/narr/renderers.rst b/docs/narr/renderers.rst index cc5baf05e..50e85813a 100644 --- a/docs/narr/renderers.rst +++ b/docs/narr/renderers.rst @@ -609,8 +609,8 @@ Pyramid supports overriding almost every aspect of its setup through its :ref:`Conflict Resolution ` mechanism. This means that, in most cases, overriding a renderer is as simple as using the :meth:`pyramid.config.Configurator.add_renderer` method to redefine the -template extension. For example, if you would like to override the ``.txt`` -extension to specify a new renderer, you could do the following: +template extension. For example, if you would like to override the ``json`` +renderer to specify a new renderer, you could do the following: .. code-block:: python -- cgit v1.2.3