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/webob.rst | 36 +++++++----------------------------- 1 file changed, 7 insertions(+), 29 deletions(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index 072ca1c74..6cd9418ce 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -362,11 +362,11 @@ To facilitate error responses like ``404 Not Found``, the module :mod:`webob.exc` contains classes for each kind of error response. These include boring, but appropriate error bodies. The exceptions exposed by this module, when used under :app:`Pyramid`, should be imported from the -:mod:`pyramid.httpexceptions` "facade" module. This import location is merely -a facade for the original location of these exceptions: ``webob.exc``. +:mod:`pyramid.response` module. This import location contains subclasses and +replacements that mirror those in the original ``webob.exc``. -Each class is named ``pyramid.httpexceptions.HTTP*``, where ``*`` is the reason -for the error. For instance, :class:`pyramid.httpexceptions.HTTPNotFound`. It +Each class is named ``pyramid.response.HTTP*``, where ``*`` is the reason for +the error. For instance, :class:`pyramid.response.HTTPNotFound`. It subclasses :class:`pyramid.Response`, so you can manipulate the instances in the same way. A typical example is: @@ -374,40 +374,18 @@ the same way. A typical example is: .. code-block:: python :linenos: - from pyramid.httpexceptions import HTTPNotFound - from pyramid.httpexceptions import HTTPMovedPermanently + from pyramid.response import HTTPNotFound + from pyramid.response import HTTPMovedPermanently response = HTTPNotFound('There is no such resource') # or: response = HTTPMovedPermanently(location=new_url) -These are not exceptions unless you are using Python 2.5+, because -they are new-style classes which are not allowed as exceptions until -Python 2.5. To get an exception object use ``response.exception``. -You can use this like: - -.. code-block:: python - :linenos: - - from pyramid.httpexceptions import HTTPException - from pyramid.httpexceptions import HTTPNotFound - - def aview(request): - try: - # ... stuff ... - raise HTTPNotFound('No such resource').exception - except HTTPException, e: - return request.get_response(e) - -The exceptions are still WSGI applications, but you cannot set -attributes like ``content_type``, ``charset``, etc. on these exception -objects. - More Details ++++++++++++ More details about the response object API are available in the :mod:`pyramid.response` documentation. More details about exception responses -are in the :mod:`pyramid.httpexceptions` API documentation. The `WebOb +are in the :mod:`pyramid.response` API documentation. The `WebOb documentation `_ is also useful. -- 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/webob.rst | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index 6cd9418ce..70ab5eea8 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -362,20 +362,21 @@ To facilitate error responses like ``404 Not Found``, the module :mod:`webob.exc` contains classes for each kind of error response. These include boring, but appropriate error bodies. The exceptions exposed by this module, when used under :app:`Pyramid`, should be imported from the -:mod:`pyramid.response` module. This import location contains subclasses and -replacements that mirror those in the original ``webob.exc``. +:mod:`pyramid.httpexceptions` module. This import location contains +subclasses and replacements that mirror those in the original ``webob.exc``. -Each class is named ``pyramid.response.HTTP*``, where ``*`` is the reason for -the error. For instance, :class:`pyramid.response.HTTPNotFound`. It -subclasses :class:`pyramid.Response`, so you can manipulate the instances in -the same way. A typical example is: +Each class is named ``pyramid.httpexceptions.HTTP*``, where ``*`` is the +reason for the error. For instance, +:class:`pyramid.httpexceptions.HTTPNotFound` subclasses +:class:`pyramid.Response`, so you can manipulate the instances in the same +way. A typical example is: .. ignore-next-block .. code-block:: python :linenos: - from pyramid.response import HTTPNotFound - from pyramid.response import HTTPMovedPermanently + from pyramid.httpexceptions import HTTPNotFound + from pyramid.httpexceptions import HTTPMovedPermanently response = HTTPNotFound('There is no such resource') # or: @@ -385,7 +386,7 @@ More Details ++++++++++++ More details about the response object API are available in the -:mod:`pyramid.response` documentation. More details about exception responses -are in the :mod:`pyramid.response` API documentation. The `WebOb -documentation `_ is also useful. +:mod:`pyramid.response` documentation. More details about exception +responses are in the :mod:`pyramid.httpexceptions` API documentation. The +`WebOb documentation `_ is also useful. -- 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/webob.rst | 66 +++++++++++++++++++++++++++-------------------------- 1 file changed, 34 insertions(+), 32 deletions(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index 70ab5eea8..0ff8e1de7 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -10,15 +10,15 @@ Request and Response Objects .. note:: This chapter is adapted from a portion of the :term:`WebOb` documentation, originally written by Ian Bicking. -:app:`Pyramid` uses the :term:`WebOb` package to supply +:app:`Pyramid` uses the :term:`WebOb` package as a basis for its :term:`request` and :term:`response` object implementations. The -:term:`request` object that is passed to a :app:`Pyramid` -:term:`view` is an instance of the :class:`pyramid.request.Request` -class, which is a subclass of :class:`webob.Request`. The -:term:`response` returned from a :app:`Pyramid` :term:`view` -:term:`renderer` is an instance of the :mod:`webob.Response` class. -Users can also return an instance of :mod:`webob.Response` directly -from a view as necessary. +:term:`request` object that is passed to a :app:`Pyramid` :term:`view` is an +instance of the :class:`pyramid.request.Request` class, which is a subclass +of :class:`webob.Request`. The :term:`response` returned from a +:app:`Pyramid` :term:`view` :term:`renderer` is an instance of the +:mod:`pyramid.response.Response` class, which is a subclass of the +:class:`webob.Response` class. Users can also return an instance of +:class:`pyramid.response.Response` directly from a view as necessary. WebOb is a project separate from :app:`Pyramid` with a separate set of authors and a fully separate `set of documentation @@ -26,16 +26,15 @@ authors and a fully separate `set of documentation standard WebOb request, which is documented in the :ref:`request_module` API documentation. -WebOb provides objects for HTTP requests and responses. Specifically -it does this by wrapping the `WSGI `_ request -environment and response status/headers/app_iter (body). +WebOb provides objects for HTTP requests and responses. Specifically it does +this by wrapping the `WSGI `_ request environment and +response status, header list, and app_iter (body) values. -WebOb request and response objects provide many conveniences for -parsing WSGI requests and forming WSGI responses. WebOb is a nice way -to represent "raw" WSGI requests and responses; however, we won't -cover that use case in this document, as users of :app:`Pyramid` -don't typically need to use the WSGI-related features of WebOb -directly. The `reference documentation +WebOb request and response objects provide many conveniences for parsing WSGI +requests and forming WSGI responses. WebOb is a nice way to represent "raw" +WSGI requests and responses; however, we won't cover that use case in this +document, as users of :app:`Pyramid` don't typically need to use the +WSGI-related features of WebOb directly. The `reference documentation `_ shows many examples of creating requests and using response objects in this manner, however. @@ -170,9 +169,9 @@ of the request. I'll show various values for an example URL Methods +++++++ -There are `several methods -`_ but -only a few you'll use often: +There are methods of request objects documented in +:class:`pyramid.request.Request` but you'll find that you won't use very many +of them. Here are a couple that might be useful: ``Request.blank(base_url)``: Creates a new request with blank information, based at the given @@ -183,9 +182,9 @@ only a few you'll use often: subrequests). ``req.get_response(wsgi_application)``: - This method calls the given WSGI application with this request, - and returns a `Response`_ object. You can also use this for - subrequests, or testing. + This method calls the given WSGI application with this request, and + returns a :class:`pyramid.response.Response` object. You can also use + this for subrequests, or testing. .. index:: single: request (and unicode) @@ -259,8 +258,10 @@ Response ~~~~~~~~ The :app:`Pyramid` response object can be imported as -:class:`pyramid.response.Response`. This import location is merely a facade -for its original location: ``webob.Response``. +:class:`pyramid.response.Response`. This class is a subclass of the +``webob.Response`` class. The subclass does not add or change any +functionality, so the WebOb Response documentation will be completely +relevant for this class as well. A response object has three fundamental parts: @@ -283,8 +284,8 @@ A response object has three fundamental parts: ``response.body_file`` (a file-like object; writing to it appends to ``app_iter``). -Everything else in the object derives from this underlying state. -Here's the highlights: +Everything else in the object typically derives from this underlying state. +Here are some highlights: ``response.content_type`` The content type *not* including the ``charset`` parameter. @@ -359,11 +360,12 @@ Exception Responses +++++++++++++++++++ To facilitate error responses like ``404 Not Found``, the module -:mod:`webob.exc` contains classes for each kind of error response. These -include boring, but appropriate error bodies. The exceptions exposed by this -module, when used under :app:`Pyramid`, should be imported from the -:mod:`pyramid.httpexceptions` module. This import location contains -subclasses and replacements that mirror those in the original ``webob.exc``. +:mod:`pyramid.httpexceptions` contains classes for each kind of error +response. These include boring, but appropriate error bodies. The +exceptions exposed by this module, when used under :app:`Pyramid`, should be +imported from the :mod:`pyramid.httpexceptions` module. This import location +contains subclasses and replacements that mirror those in the ``webob.exc`` +module. Each class is named ``pyramid.httpexceptions.HTTP*``, where ``*`` is the reason for the error. For instance, -- cgit v1.2.3 From 6a0602b3ce4d2a6de9dca25d8e0d390796a79267 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Sat, 9 Jul 2011 21:12:06 -0400 Subject: request.json -> request.json_body; add some docs for json_body --- docs/narr/webob.rst | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index 0ff8e1de7..373ae5896 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -78,6 +78,10 @@ object: ``PUT``. You can also get ``req.body_file`` for a file-like object. +``req.json_body`` + The JSON-decoded contents of the body of the request. See + :ref:`request_json_body`. + ``req.cookies``: A simple dictionary of all the cookies. @@ -239,6 +243,57 @@ tuples; all the keys are ordered, and all the values are ordered. API documentation for a multidict exists as :class:`pyramid.interfaces.IMultiDict`. +.. _request_json_body: + +Dealing With A JSON-Encoded Request Body +++++++++++++++++++++++++++++++++++++++++ + +.. note:: this feature is new as of Pyramid 1.1. + +:attr:`pyramid.request.Request.json_body` is a property that returns a +:term:`JSON` -decoded representation of the request body. If the request +does not have a body, or the body is not a properly JSON-encoded value, an +exception will be raised when this attribute is accessed. + +This attribute is useful when you invoke a Pyramid view callable via +e.g. jQuery's ``$.post`` or ``$.ajax`` functions, which have the potential to +send a JSON-encoded body or parameters. + +Using ``request.json_body`` is equivalent to: + +.. code-block:: python + + from json import loads + loads(request.body, encoding=request.charset) + +Here's how to construct an AJAX request in Javascript using :term:`jQuery` +that allows you to use the ``request.json_body`` attribute when the request +is sent to a Pyramid application: + +.. code-block:: javascript + + jQuery.ajax({type:'POST', + url: 'http://localhost:6543/', // the pyramid server + data: JSON.stringify({'a':1}), + contentType: 'application/json; charset=utf-8', + dataType: 'json'}); + +When such a request reaches a view in your application, the +``request.json_body`` attribute will be available in the view callable body. + +.. code-block:: javascript + + @view_config(renderer='json') + def aview(request): + print request.json_body + return {'result':'OK'} + +For the above view, printed to the console will be: + +.. code-block:: python + + {u'a': 1} + More Details ++++++++++++ -- cgit v1.2.3 From e3349693c533c17fb9b6a770a8360b64ec337c68 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Sat, 9 Jul 2011 21:24:14 -0400 Subject: make less confusing --- docs/narr/webob.rst | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index 373ae5896..beb319084 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -256,8 +256,8 @@ does not have a body, or the body is not a properly JSON-encoded value, an exception will be raised when this attribute is accessed. This attribute is useful when you invoke a Pyramid view callable via -e.g. jQuery's ``$.post`` or ``$.ajax`` functions, which have the potential to -send a JSON-encoded body or parameters. +e.g. jQuery's ``$.ajax`` function, which has the potential to send a request +with a JSON-encoded body. Using ``request.json_body`` is equivalent to: @@ -275,18 +275,17 @@ is sent to a Pyramid application: jQuery.ajax({type:'POST', url: 'http://localhost:6543/', // the pyramid server data: JSON.stringify({'a':1}), - contentType: 'application/json; charset=utf-8', - dataType: 'json'}); + contentType: 'application/json; charset=utf-8'}); When such a request reaches a view in your application, the ``request.json_body`` attribute will be available in the view callable body. .. code-block:: javascript - @view_config(renderer='json') + @view_config(renderer='string') def aview(request): print request.json_body - return {'result':'OK'} + return 'OK' For the above view, printed to the console will be: -- cgit v1.2.3 From e005c27ae54f12d5f9579451c1c894a534eb7d48 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Sun, 10 Jul 2011 22:06:51 -0500 Subject: Modified docs to reference webob's new website. --- docs/narr/webob.rst | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index beb319084..0d928e532 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -22,9 +22,9 @@ of :class:`webob.Request`. The :term:`response` returned from a WebOb is a project separate from :app:`Pyramid` with a separate set of authors and a fully separate `set of documentation -`_. Pyramid adds some functionality to the -standard WebOb request, which is documented in the :ref:`request_module` API -documentation. +`_. Pyramid adds some +functionality to the standard WebOb request, which is documented in the +:ref:`request_module` API documentation. WebOb provides objects for HTTP requests and responses. Specifically it does this by wrapping the `WSGI `_ request environment and @@ -35,7 +35,7 @@ requests and forming WSGI responses. WebOb is a nice way to represent "raw" WSGI requests and responses; however, we won't cover that use case in this document, as users of :app:`Pyramid` don't typically need to use the WSGI-related features of WebOb directly. The `reference documentation -`_ shows many examples of +`_ shows many examples of creating requests and using response objects in this manner, however. .. index:: @@ -300,8 +300,8 @@ More detail about the request object API is available in: - The :class:`pyramid.request.Request` API documentation. -- The `WebOb documentation `_. All - methods and attributes of a ``webob.Request`` documented within the +- The `WebOb documentation `_. + All methods and attributes of a ``webob.Request`` documented within the WebOb documentation will work with request objects created by :app:`Pyramid`. @@ -385,7 +385,7 @@ properties. These are parsed, so you can do things like ``response.last_modified = os.path.getmtime(filename)``. The details are available in the `extracted Response documentation -`_. +`_. .. index:: single: response (creating) @@ -444,5 +444,6 @@ More Details More details about the response object API are available in the :mod:`pyramid.response` documentation. More details about exception responses are in the :mod:`pyramid.httpexceptions` API documentation. The -`WebOb documentation `_ is also useful. +`WebOb documentation `_ is also +useful. -- 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/webob.rst | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index 0d928e532..6e8c39523 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -243,6 +243,9 @@ tuples; all the keys are ordered, and all the values are ordered. API documentation for a multidict exists as :class:`pyramid.interfaces.IMultiDict`. +.. index:: + pair: json_body; request + .. _request_json_body: Dealing With A JSON-Encoded Request Body @@ -408,7 +411,7 @@ anything, though if you subclass :class:`pyramid.response.Response` and set ``default_content_type`` you can override this behavior. .. index:: - single: response exceptions + single: exception responses Exception Responses +++++++++++++++++++ -- cgit v1.2.3 From 0b0b2065558649c0af65a08e94cd99894889bea3 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Thu, 21 Jul 2011 14:41:22 -0400 Subject: urllib2 example of creating a request suitable for producing a json body --- docs/narr/webob.rst | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index 6e8c39523..106024db3 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -296,6 +296,20 @@ For the above view, printed to the console will be: {u'a': 1} +For bonus points, here's a bit of client-side code that will produce a +request that has a body suitable for reading via ``request.json_body`` using +Python's ``urllib2`` instead of a Javascript AJAX request: + +.. code-block:: python + + import urllib2 + import json + + json_payload = json.dumps({'a':1}) + headers = {'Content-Type':'application/json; charset=utf-8'} + req = urllib2.Request('http://localhost:6543/', json_payload, headers) + resp = urllib2.urlopen(req) + More Details ++++++++++++ -- cgit v1.2.3 From b37b97bb67eedced5c6a2e0fec718594b5d41878 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Mon, 5 Sep 2011 17:58:34 -0400 Subject: move unrelated request cleanup to webob.rest; reorder urldispatch chapter from most-important-concept-to-least --- docs/narr/webob.rst | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index 106024db3..21c368350 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -310,6 +310,53 @@ Python's ``urllib2`` instead of a Javascript AJAX request: req = urllib2.Request('http://localhost:6543/', json_payload, headers) resp = urllib2.urlopen(req) +.. index:: + single: cleaning up after request + +.. _cleaning_up_after_a_request: + +Cleaning Up After a Request ++++++++++++++++++++++++++++ + +Sometimes it's required that some cleanup be performed at the end of a +request when a database connection is involved. + +For example, let's say you have a ``mypackage`` :app:`Pyramid` application +package that uses SQLAlchemy, and you'd like the current SQLAlchemy database +session to be removed after each request. Put the following in the +``mypackage.__init__`` module: + +.. ignore-next-block +.. code-block:: python + :linenos: + + from mypackage.models import DBSession + + from pyramid.events import subscriber + from pyramid.events import NewRequest + + def cleanup_callback(request): + DBSession.remove() + + @subscriber(NewRequest) + def add_cleanup_callback(event): + event.request.add_finished_callback(cleanup_callback) + +Registering the ``cleanup_callback`` finished callback at the start of a +request (by causing the ``add_cleanup_callback`` to receive a +:class:`pyramid.events.NewRequest` event at the start of each request) will +cause the DBSession to be removed whenever request processing has ended. +Note that in the example above, for the :class:`pyramid.events.subscriber` +decorator to "work", the :meth:`pyramid.config.Configurator.scan` method must +be called against your ``mypackage`` package during application +initialization. + +.. note:: This is only an example. In particular, it is not necessary to + cause ``DBSession.remove`` to be called in an application generated from + any :app:`Pyramid` scaffold, because these all use the ``pyramid_tm`` + package. The cleanup done by ``DBSession.remove`` is unnecessary when + ``pyramid_tm`` middleware is configured into the application. + More Details ++++++++++++ -- cgit v1.2.3 From 01eac92dcdbe0d51b75783350997e69a7613da9e Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Fri, 24 Feb 2012 15:15:18 -0500 Subject: docs-deprecate tmpl_context --- docs/narr/webob.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index 21c368350..a8c11acec 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -117,8 +117,8 @@ Special Attributes Added to the Request by :app:`Pyramid` In addition to the standard :term:`WebOb` attributes, :app:`Pyramid` adds special attributes to every request: ``context``, ``registry``, ``root``, ``subpath``, ``traversed``, ``view_name``, ``virtual_root``, -``virtual_root_path``, ``session``, and ``tmpl_context``, ``matchdict``, and -``matched_route``. These attributes are documented further within the +``virtual_root_path``, ``session``, ``matchdict``, and ``matched_route``. +These attributes are documented further within the :class:`pyramid.request.Request` API documentation. .. index:: -- cgit v1.2.3 From 40dbf42a2df1783c3d803adf950380c21512bb91 Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Wed, 30 Jan 2013 00:41:23 +0200 Subject: use the more appropriate directives --- docs/narr/webob.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index a8c11acec..44940f9e6 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -251,7 +251,7 @@ API documentation for a multidict exists as Dealing With A JSON-Encoded Request Body ++++++++++++++++++++++++++++++++++++++++ -.. note:: this feature is new as of Pyramid 1.1. +.. versionadded:: 1.1 :attr:`pyramid.request.Request.json_body` is a property that returns a :term:`JSON` -decoded representation of the request body. If the request -- cgit v1.2.3 From 1ad8de2b9032b5a452b75274b8f908645c732e57 Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Fri, 22 Mar 2013 17:24:32 +0200 Subject: remove unused ignore-next-block directive --- docs/narr/webob.rst | 2 -- 1 file changed, 2 deletions(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index 44940f9e6..63a08adaa 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -326,7 +326,6 @@ package that uses SQLAlchemy, and you'd like the current SQLAlchemy database session to be removed after each request. Put the following in the ``mypackage.__init__`` module: -.. ignore-next-block .. code-block:: python :linenos: @@ -491,7 +490,6 @@ reason for the error. For instance, :class:`pyramid.Response`, so you can manipulate the instances in the same way. A typical example is: -.. ignore-next-block .. code-block:: python :linenos: -- cgit v1.2.3 From 37607c3a9382de7c3757799791a91b80e2d9888d Mon Sep 17 00:00:00 2001 From: Catalin Iacob Date: Sun, 31 Mar 2013 14:33:24 +0200 Subject: Consistently link middleware term to the glossary --- docs/narr/webob.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index 63a08adaa..02c03c8db 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -354,7 +354,7 @@ initialization. cause ``DBSession.remove`` to be called in an application generated from any :app:`Pyramid` scaffold, because these all use the ``pyramid_tm`` package. The cleanup done by ``DBSession.remove`` is unnecessary when - ``pyramid_tm`` middleware is configured into the application. + ``pyramid_tm`` :term:`middleware` is configured into the application. More Details ++++++++++++ -- cgit v1.2.3 From f758ec6487bb3b57fb5b1c3aa9ac1f28930d6bd8 Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Fri, 5 Apr 2013 00:00:44 +0200 Subject: fix some cross-references --- docs/narr/webob.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index 02c03c8db..c0ca450b1 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -487,7 +487,7 @@ module. Each class is named ``pyramid.httpexceptions.HTTP*``, where ``*`` is the reason for the error. For instance, :class:`pyramid.httpexceptions.HTTPNotFound` subclasses -:class:`pyramid.Response`, so you can manipulate the instances in the same +:class:`pyramid.response.Response`, so you can manipulate the instances in the same way. A typical example is: .. code-block:: python -- cgit v1.2.3 From edfc4f80a1240f6f5f0c41e53078a8f5d305075f Mon Sep 17 00:00:00 2001 From: Philip Jenvey Date: Thu, 15 Aug 2013 15:57:14 -0700 Subject: prefer the functionish print --- docs/narr/webob.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index c0ca450b1..f0a4b5a0b 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -287,7 +287,7 @@ When such a request reaches a view in your application, the @view_config(renderer='string') def aview(request): - print request.json_body + print(request.json_body) return 'OK' For the above view, printed to the console will be: -- cgit v1.2.3 From ac16ec2f722dcdaa45d0389ad87952bd6be6e389 Mon Sep 17 00:00:00 2001 From: westurner Date: Tue, 15 Apr 2014 01:28:03 -0500 Subject: DOC: Response.content_type defaults to text/html --- docs/narr/webob.rst | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index f0a4b5a0b..6a331e4bf 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -408,6 +408,8 @@ Here are some highlights: The content type *not* including the ``charset`` parameter. Typical use: ``response.content_type = 'text/html'``. + Default value: ``response.content_type = 'text/html'``. + ``response.charset``: The ``charset`` parameter of the content-type, it also informs encoding in ``response.unicode_body``. @@ -466,9 +468,12 @@ argument to the class; e.g.: from pyramid.response import Response response = Response(body='hello world!', content_type='text/plain') -The status defaults to ``'200 OK'``. The content_type does not default to -anything, though if you subclass :class:`pyramid.response.Response` and set -``default_content_type`` you can override this behavior. +The status defaults to ``'200 OK'``. + +The value of content_type defaults to +``webob.response.Response.default_content_type``; which is `text/html`. +You can subclass :class:`pyramid.response.Response` and set +``default_content_type`` to override this behavior. .. index:: single: exception responses -- cgit v1.2.3 From 2711913daac645dc1960074d6c5121c8fb49b772 Mon Sep 17 00:00:00 2001 From: Adrian Teng Date: Wed, 17 Dec 2014 00:06:27 +0000 Subject: Add documentation on handling CORS pre-flights --- docs/narr/webob.rst | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index 6a331e4bf..7d459a1f5 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -310,6 +310,10 @@ Python's ``urllib2`` instead of a Javascript AJAX request: req = urllib2.Request('http://localhost:6543/', json_payload, headers) resp = urllib2.urlopen(req) +If you are doing Cross-origin resource sharing (CORS), then the standard requires the browser to do a pre-flight HTTP OPTIONS request. The easiest way to handling this is adding an extra ``view_config`` for the same route, with ``request_method`` set to ``OPTIONS``, and setting the desired response header before returning. You can find examples of response headers here_. + +.. _here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests + .. index:: single: cleaning up after request -- cgit v1.2.3 From 2660f5053de5383aacf4ceff3d4e05d7e73f1635 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Tue, 16 Dec 2014 19:54:03 -0500 Subject: 79 cols --- docs/narr/webob.rst | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index 7d459a1f5..0eb070b06 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -310,7 +310,11 @@ Python's ``urllib2`` instead of a Javascript AJAX request: req = urllib2.Request('http://localhost:6543/', json_payload, headers) resp = urllib2.urlopen(req) -If you are doing Cross-origin resource sharing (CORS), then the standard requires the browser to do a pre-flight HTTP OPTIONS request. The easiest way to handling this is adding an extra ``view_config`` for the same route, with ``request_method`` set to ``OPTIONS``, and setting the desired response header before returning. You can find examples of response headers here_. +If you are doing Cross-origin resource sharing (CORS), then the standard +requires the browser to do a pre-flight HTTP OPTIONS request. The easiest way +to handling this is adding an extra ``view_config`` for the same route, with +``request_method`` set to ``OPTIONS``, and setting the desired response header +before returning. You can find examples of response headers here_. .. _here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests -- cgit v1.2.3 From 8447260de970629be01de821e43e9ea33e4405a0 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Wed, 15 Jul 2015 01:44:01 -0400 Subject: fix for #1846, incorrect pointers to nonexistent webob properties --- docs/narr/webob.rst | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index 0eb070b06..f82cf6fbe 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -191,25 +191,21 @@ of them. Here are a couple that might be useful: this for subrequests, or testing. .. index:: - single: request (and unicode) - single: unicode (and the request) + single: request (and text/unicode) + single: unicode and text (and the request) -Unicode -+++++++ +Text (Unicode) +++++++++++++++ -Many of the properties in the request object will return unicode -values if the request encoding/charset is provided. The client *can* +Many of the properties of the request object will be text values (``unicode`` +under Python 2 or ``str`` under Python 3) if the request encoding/charset is +provided. If it is provided, the values in ``req.POST``, ``req.GET``, +``req.params``, and ``req.cookies`` will contain text. The client *can* indicate the charset with something like ``Content-Type: -application/x-www-form-urlencoded; charset=utf8``, but browsers seldom -set this. You can set the charset with ``req.charset = 'utf8'``, or -during instantiation with ``Request(environ, charset='utf8')``. If -you subclass ``Request`` you can also set ``charset`` as a class-level -attribute. - -If it is set, then ``req.POST``, ``req.GET``, ``req.params``, and -``req.cookies`` will contain unicode strings. Each has a -corresponding ``req.str_*`` (e.g., ``req.str_POST``) that is always -a ``str``, and never unicode. +application/x-www-form-urlencoded; charset=utf8``, but browsers seldom set +this. You can reset the charset of an existing request with ``newreq = +req.decode('utf-8')``, or during instantiation with ``Request(environ, +charset='utf8')``. .. index:: single: multidict (WebOb) @@ -404,7 +400,7 @@ A response object has three fundamental parts: ``response.app_iter``: An iterable (such as a list or generator) that will produce the content of the response. This is also accessible as - ``response.body`` (a string), ``response.unicode_body`` (a + ``response.body`` (a string), ``response.text`` (a unicode object, informed by ``response.charset``), and ``response.body_file`` (a file-like object; writing to it appends to ``app_iter``). @@ -420,7 +416,7 @@ Here are some highlights: ``response.charset``: The ``charset`` parameter of the content-type, it also informs - encoding in ``response.unicode_body``. + encoding in ``response.text``. ``response.content_type_params`` is a dictionary of all the parameters. -- cgit v1.2.3 From e0d42dbd2e8570324439816fa204a6c907fbe894 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Thu, 15 Oct 2015 22:59:53 -0700 Subject: minor grammar, rewrap 79 cols, update dead external links, .rst syntax, git mah intersphinx on yo! --- docs/narr/webob.rst | 423 +++++++++++++++++++++++++--------------------------- 1 file changed, 201 insertions(+), 222 deletions(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index f82cf6fbe..f18cf1dfb 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -13,26 +13,26 @@ Request and Response Objects :app:`Pyramid` uses the :term:`WebOb` package as a basis for its :term:`request` and :term:`response` object implementations. The :term:`request` object that is passed to a :app:`Pyramid` :term:`view` is an -instance of the :class:`pyramid.request.Request` class, which is a subclass -of :class:`webob.Request`. The :term:`response` returned from a -:app:`Pyramid` :term:`view` :term:`renderer` is an instance of the +instance of the :class:`pyramid.request.Request` class, which is a subclass of +:class:`webob.Request`. The :term:`response` returned from a :app:`Pyramid` +:term:`view` :term:`renderer` is an instance of the :mod:`pyramid.response.Response` class, which is a subclass of the :class:`webob.Response` class. Users can also return an instance of :class:`pyramid.response.Response` directly from a view as necessary. -WebOb is a project separate from :app:`Pyramid` with a separate set of -authors and a fully separate `set of documentation -`_. Pyramid adds some +WebOb is a project separate from :app:`Pyramid` with a separate set of authors +and a fully separate `set of documentation +`_. :app:`Pyramid` adds some functionality to the standard WebOb request, which is documented in the :ref:`request_module` API documentation. WebOb provides objects for HTTP requests and responses. Specifically it does -this by wrapping the `WSGI `_ request environment and -response status, header list, and app_iter (body) values. +this by wrapping the `WSGI `_ request environment and response +status, header list, and app_iter (body) values. WebOb request and response objects provide many conveniences for parsing WSGI requests and forming WSGI responses. WebOb is a nice way to represent "raw" -WSGI requests and responses; however, we won't cover that use case in this +WSGI requests and responses. However, we won't cover that use case in this document, as users of :app:`Pyramid` don't typically need to use the WSGI-related features of WebOb directly. The `reference documentation `_ shows many examples of @@ -47,64 +47,58 @@ Request The request object is a wrapper around the `WSGI environ dictionary `_. This -dictionary contains keys for each header, keys that describe the -request (including the path and query string), a file-like object for -the request body, and a variety of custom keys. You can always access -the environ with ``req.environ``. +dictionary contains keys for each header, keys that describe the request +(including the path and query string), a file-like object for the request body, +and a variety of custom keys. You can always access the environ with +``req.environ``. -Some of the most important/interesting attributes of a request -object: +Some of the most important and interesting attributes of a request object are +below. -``req.method``: - The request method, e.g., ``'GET'``, ``'POST'`` +``req.method`` + The request method, e.g., ``GET``, ``POST`` -``req.GET``: - A :term:`multidict` with all the variables in the query - string. +``req.GET`` + A :term:`multidict` with all the variables in the query string. -``req.POST``: - A :term:`multidict` with all the variables in the request - body. This only has variables if the request was a ``POST`` and - it is a form submission. +``req.POST`` + A :term:`multidict` with all the variables in the request body. This only + has variables if the request was a ``POST`` and it is a form submission. -``req.params``: - A :term:`multidict` with a combination of everything in - ``req.GET`` and ``req.POST``. +``req.params`` + A :term:`multidict` with a combination of everything in ``req.GET`` and + ``req.POST``. -``req.body``: - The contents of the body of the request. This contains the entire - request body as a string. This is useful when the request is a - ``POST`` that is *not* a form submission, or a request like a - ``PUT``. You can also get ``req.body_file`` for a file-like - object. +``req.body`` + The contents of the body of the request. This contains the entire request + body as a string. This is useful when the request is a ``POST`` that is + *not* a form submission, or a request like a ``PUT``. You can also get + ``req.body_file`` for a file-like object. ``req.json_body`` The JSON-decoded contents of the body of the request. See :ref:`request_json_body`. -``req.cookies``: +``req.cookies`` A simple dictionary of all the cookies. -``req.headers``: +``req.headers`` A dictionary of all the headers. This dictionary is case-insensitive. -``req.urlvars`` and ``req.urlargs``: - ``req.urlvars`` are the keyword parameters associated with the - request URL. ``req.urlargs`` are the positional parameters. - These are set by products like `Routes - `_ and `Selector - `_. +``req.urlvars`` and ``req.urlargs`` + ``req.urlvars`` are the keyword parameters associated with the request URL. + ``req.urlargs`` are the positional parameters. These are set by products + like `Routes `_ and `Selector + `_. -Also, for standard HTTP request headers there are usually attributes, -for instance: ``req.accept_language``, ``req.content_length``, -``req.user_agent``, as an example. These properties expose the -*parsed* form of each header, for whatever parsing makes sense. For -instance, ``req.if_modified_since`` returns a `datetime -`_ object -(or None if the header is was not provided). +Also for standard HTTP request headers, there are usually attributes such as +``req.accept_language``, ``req.content_length``, and ``req.user_agent``. These +properties expose the *parsed* form of each header, for whatever parsing makes +sense. For instance, ``req.if_modified_since`` returns a :mod:`datetime` +object (or None if the header is was not provided). -.. note:: Full API documentation for the :app:`Pyramid` request - object is available in :ref:`request_module`. +.. note:: Full API documentation for the :app:`Pyramid` request object is + available in :ref:`request_module`. .. index:: single: request attributes (special) @@ -112,14 +106,14 @@ instance, ``req.if_modified_since`` returns a `datetime .. _special_request_attributes: Special Attributes Added to the Request by :app:`Pyramid` -++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ In addition to the standard :term:`WebOb` attributes, :app:`Pyramid` adds special attributes to every request: ``context``, ``registry``, ``root``, ``subpath``, ``traversed``, ``view_name``, ``virtual_root``, -``virtual_root_path``, ``session``, ``matchdict``, and ``matched_route``. -These attributes are documented further within the -:class:`pyramid.request.Request` API documentation. +``virtual_root_path``, ``session``, ``matchdict``, and ``matched_route``. These +attributes are documented further within the :class:`pyramid.request.Request` +API documentation. .. index:: single: request URLs @@ -127,45 +121,43 @@ These attributes are documented further within the URLs ++++ -In addition to these attributes, there are several ways to get the URL -of the request. I'll show various values for an example URL +In addition to these attributes, there are several ways to get the URL of the +request and its parts. We'll show various values for an example URL ``http://localhost/app/blog?id=10``, where the application is mounted at ``http://localhost/app``. -``req.url``: - The full request URL, with query string, e.g., +``req.url`` + The full request URL with query string, e.g., ``http://localhost/app/blog?id=10`` -``req.host``: - The host information in the URL, e.g., - ``localhost`` +``req.host`` + The host information in the URL, e.g., ``localhost`` -``req.host_url``: +``req.host_url`` The URL with the host, e.g., ``http://localhost`` -``req.application_url``: - The URL of the application (just the SCRIPT_NAME portion of the - path, not PATH_INFO). E.g., ``http://localhost/app`` +``req.application_url`` + The URL of the application (just the ``SCRIPT_NAME`` portion of the path, + not ``PATH_INFO``), e.g., ``http://localhost/app`` -``req.path_url``: - The URL of the application including the PATH_INFO. e.g., +``req.path_url`` + The URL of the application including the ``PATH_INFO``, e.g., ``http://localhost/app/blog`` -``req.path``: - The URL including PATH_INFO without the host or scheme. e.g., +``req.path`` + The URL including ``PATH_INFO`` without the host or scheme, e.g., ``/app/blog`` -``req.path_qs``: - The URL including PATH_INFO and the query string. e.g, +``req.path_qs`` + The URL including ``PATH_INFO`` and the query string, e.g, ``/app/blog?id=10`` -``req.query_string``: - The query string in the URL, e.g., - ``id=10`` +``req.query_string`` + The query string in the URL, e.g., ``id=10`` -``req.relative_url(url, to_application=False)``: - Gives a URL, relative to the current URL. If ``to_application`` - is True, then resolves it relative to ``req.application_url``. +``req.relative_url(url, to_application=False)`` + Gives a URL relative to the current URL. If ``to_application`` is True, + then resolves it relative to ``req.application_url``. .. index:: single: request methods @@ -177,18 +169,17 @@ There are methods of request objects documented in :class:`pyramid.request.Request` but you'll find that you won't use very many of them. Here are a couple that might be useful: -``Request.blank(base_url)``: - Creates a new request with blank information, based at the given - URL. This can be useful for subrequests and artificial requests. - You can also use ``req.copy()`` to copy an existing request, or - for subrequests ``req.copy_get()`` which copies the request but - always turns it into a GET (which is safer to share for - subrequests). +``Request.blank(base_url)`` + Creates a new request with blank information, based at the given URL. This + can be useful for subrequests and artificial requests. You can also use + ``req.copy()`` to copy an existing request, or for subrequests + ``req.copy_get()`` which copies the request but always turns it into a GET + (which is safer to share for subrequests). -``req.get_response(wsgi_application)``: - This method calls the given WSGI application with this request, and - returns a :class:`pyramid.response.Response` object. You can also use - this for subrequests, or testing. +``req.get_response(wsgi_application)`` + This method calls the given WSGI application with this request, and returns + a :class:`pyramid.response.Response` object. You can also use this for + subrequests or testing. .. index:: single: request (and text/unicode) @@ -215,26 +206,25 @@ charset='utf8')``. Multidict +++++++++ -Several attributes of a WebOb request are "multidict"; structures (such as +Several attributes of a WebOb request are multidict structures (such as ``request.GET``, ``request.POST``, and ``request.params``). A multidict is a -dictionary where a key can have multiple values. The quintessential example -is a query string like ``?pref=red&pref=blue``; the ``pref`` variable has two +dictionary where a key can have multiple values. The quintessential example is +a query string like ``?pref=red&pref=blue``; the ``pref`` variable has two values: ``red`` and ``blue``. -In a multidict, when you do ``request.GET['pref']`` you'll get back -only ``'blue'`` (the last value of ``pref``). Sometimes returning a -string, and sometimes returning a list, is the cause of frequent -exceptions. If you want *all* the values back, use -``request.GET.getall('pref')``. If you want to be sure there is *one -and only one* value, use ``request.GET.getone('pref')``, which will -raise an exception if there is zero or more than one value for -``pref``. - -When you use operations like ``request.GET.items()`` you'll get back -something like ``[('pref', 'red'), ('pref', 'blue')]``. All the -key/value pairs will show up. Similarly ``request.GET.keys()`` -returns ``['pref', 'pref']``. Multidict is a view on a list of -tuples; all the keys are ordered, and all the values are ordered. +In a multidict, when you do ``request.GET['pref']``, you'll get back only +``"blue"`` (the last value of ``pref``). This returned result might not be +expected—sometimes returning a string, and sometimes returning a list—and may +be cause of frequent exceptions. If you want *all* the values back, use +``request.GET.getall('pref')``. If you want to be sure there is *one and only +one* value, use ``request.GET.getone('pref')``, which will raise an exception +if there is zero or more than one value for ``pref``. + +When you use operations like ``request.GET.items()``, you'll get back something +like ``[('pref', 'red'), ('pref', 'blue')]``. All the key/value pairs will +show up. Similarly ``request.GET.keys()`` returns ``['pref', 'pref']``. +Multidict is a view on a list of tuples; all the keys are ordered, and all the +values are ordered. API documentation for a multidict exists as :class:`pyramid.interfaces.IMultiDict`. @@ -244,19 +234,19 @@ API documentation for a multidict exists as .. _request_json_body: -Dealing With A JSON-Encoded Request Body +Dealing with a JSON-Encoded Request Body ++++++++++++++++++++++++++++++++++++++++ .. versionadded:: 1.1 :attr:`pyramid.request.Request.json_body` is a property that returns a -:term:`JSON` -decoded representation of the request body. If the request -does not have a body, or the body is not a properly JSON-encoded value, an -exception will be raised when this attribute is accessed. +:term:`JSON`-decoded representation of the request body. If the request does +not have a body, or the body is not a properly JSON-encoded value, an exception +will be raised when this attribute is accessed. -This attribute is useful when you invoke a Pyramid view callable via -e.g. jQuery's ``$.ajax`` function, which has the potential to send a request -with a JSON-encoded body. +This attribute is useful when you invoke a :app:`Pyramid` view callable via, +for example, jQuery's ``$.ajax`` function, which has the potential to send a +request with a JSON-encoded body. Using ``request.json_body`` is equivalent to: @@ -265,15 +255,15 @@ Using ``request.json_body`` is equivalent to: from json import loads loads(request.body, encoding=request.charset) -Here's how to construct an AJAX request in Javascript using :term:`jQuery` -that allows you to use the ``request.json_body`` attribute when the request -is sent to a Pyramid application: +Here's how to construct an AJAX request in JavaScript using :term:`jQuery` that +allows you to use the ``request.json_body`` attribute when the request is sent +to a :app:`Pyramid` application: .. code-block:: javascript - jQuery.ajax({type:'POST', + jQuery.ajax({type:'POST', url: 'http://localhost:6543/', // the pyramid server - data: JSON.stringify({'a':1}), + data: JSON.stringify({'a':1}), contentType: 'application/json; charset=utf-8'}); When such a request reaches a view in your application, the @@ -292,14 +282,14 @@ For the above view, printed to the console will be: {u'a': 1} -For bonus points, here's a bit of client-side code that will produce a -request that has a body suitable for reading via ``request.json_body`` using -Python's ``urllib2`` instead of a Javascript AJAX request: +For bonus points, here's a bit of client-side code that will produce a request +that has a body suitable for reading via ``request.json_body`` using Python's +``urllib2`` instead of a JavaScript AJAX request: .. code-block:: python import urllib2 - import json + import json json_payload = json.dumps({'a':1}) headers = {'Content-Type':'application/json; charset=utf-8'} @@ -308,22 +298,22 @@ Python's ``urllib2`` instead of a Javascript AJAX request: If you are doing Cross-origin resource sharing (CORS), then the standard requires the browser to do a pre-flight HTTP OPTIONS request. The easiest way -to handling this is adding an extra ``view_config`` for the same route, with -``request_method`` set to ``OPTIONS``, and setting the desired response header -before returning. You can find examples of response headers here_. - -.. _here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests +to handle this is to add an extra ``view_config`` for the same route, with +``request_method`` set to ``OPTIONS``, and set the desired response header +before returning. You can find examples of response headers `Access control +CORS, Preflighted requests +`_. .. index:: single: cleaning up after request .. _cleaning_up_after_a_request: -Cleaning Up After a Request +Cleaning up after a Request +++++++++++++++++++++++++++ -Sometimes it's required that some cleanup be performed at the end of a -request when a database connection is involved. +Sometimes it's required to perform some cleanup at the end of a request when a +database connection is involved. For example, let's say you have a ``mypackage`` :app:`Pyramid` application package that uses SQLAlchemy, and you'd like the current SQLAlchemy database @@ -348,29 +338,28 @@ session to be removed after each request. Put the following in the Registering the ``cleanup_callback`` finished callback at the start of a request (by causing the ``add_cleanup_callback`` to receive a :class:`pyramid.events.NewRequest` event at the start of each request) will -cause the DBSession to be removed whenever request processing has ended. -Note that in the example above, for the :class:`pyramid.events.subscriber` -decorator to "work", the :meth:`pyramid.config.Configurator.scan` method must -be called against your ``mypackage`` package during application -initialization. - -.. note:: This is only an example. In particular, it is not necessary to - cause ``DBSession.remove`` to be called in an application generated from - any :app:`Pyramid` scaffold, because these all use the ``pyramid_tm`` - package. The cleanup done by ``DBSession.remove`` is unnecessary when - ``pyramid_tm`` :term:`middleware` is configured into the application. +cause the DBSession to be removed whenever request processing has ended. Note +that in the example above, for the :class:`pyramid.events.subscriber` decorator +to work, the :meth:`pyramid.config.Configurator.scan` method must be called +against your ``mypackage`` package during application initialization. + +.. note:: + This is only an example. In particular, it is not necessary to cause + ``DBSession.remove`` to be called in an application generated from any + :app:`Pyramid` scaffold, because these all use the ``pyramid_tm`` package. + The cleanup done by ``DBSession.remove`` is unnecessary when ``pyramid_tm`` + :term:`middleware` is configured into the application. More Details ++++++++++++ -More detail about the request object API is available in: +More detail about the request object API is available as follows. -- The :class:`pyramid.request.Request` API documentation. +- :class:`pyramid.request.Request` API documentation -- The `WebOb documentation `_. - All methods and attributes of a ``webob.Request`` documented within the - WebOb documentation will work with request objects created by - :app:`Pyramid`. +- `WebOb documentation `_. All + methods and attributes of a ``webob.Request`` documented within the WebOb + documentation will work with request objects created by :app:`Pyramid`. .. index:: single: response object @@ -381,67 +370,62 @@ Response The :app:`Pyramid` response object can be imported as :class:`pyramid.response.Response`. This class is a subclass of the ``webob.Response`` class. The subclass does not add or change any -functionality, so the WebOb Response documentation will be completely -relevant for this class as well. +functionality, so the WebOb Response documentation will be completely relevant +for this class as well. A response object has three fundamental parts: -``response.status``: - The response code plus reason message, like ``'200 OK'``. To set - the code without a message, use ``status_int``, i.e.: - ``response.status_int = 200``. - -``response.headerlist``: - A list of all the headers, like ``[('Content-Type', - 'text/html')]``. There's a case-insensitive :term:`multidict` - in ``response.headers`` that also allows you to access - these same headers. - -``response.app_iter``: - An iterable (such as a list or generator) that will produce the - content of the response. This is also accessible as - ``response.body`` (a string), ``response.text`` (a - unicode object, informed by ``response.charset``), and - ``response.body_file`` (a file-like object; writing to it appends - to ``app_iter``). +``response.status`` + The response code plus reason message, like ``200 OK``. To set the code + without a message, use ``status_int``, i.e., ``response.status_int = 200``. + +``response.headerlist`` + A list of all the headers, like ``[('Content-Type', 'text/html')]``. + There's a case-insensitive :term:`multidict` in ``response.headers`` that + also allows you to access these same headers. + +``response.app_iter`` + An iterable (such as a list or generator) that will produce the content of + the response. This is also accessible as ``response.body`` (a string), + ``response.text`` (a unicode object, informed by ``response.charset``), and + ``response.body_file`` (a file-like object; writing to it appends to + ``app_iter``). Everything else in the object typically derives from this underlying state. Here are some highlights: ``response.content_type`` The content type *not* including the ``charset`` parameter. + Typical use: ``response.content_type = 'text/html'``. Default value: ``response.content_type = 'text/html'``. -``response.charset``: - The ``charset`` parameter of the content-type, it also informs - encoding in ``response.text``. - ``response.content_type_params`` is a dictionary of all the - parameters. - -``response.set_cookie(key, value, max_age=None, path='/', ...)``: - Set a cookie. The keyword arguments control the various cookie - parameters. The ``max_age`` argument is the length for the cookie - to live in seconds (you may also use a timedelta object). The - ``Expires`` key will also be set based on the value of - ``max_age``. - -``response.delete_cookie(key, path='/', domain=None)``: - Delete a cookie from the client. This sets ``max_age`` to 0 and - the cookie value to ``''``. - -``response.cache_expires(seconds=0)``: - This makes this response cacheable for the given number of seconds, - or if ``seconds`` is 0 then the response is uncacheable (this also - sets the ``Expires`` header). - -``response(environ, start_response)``: - The response object is a WSGI application. As an application, it - acts according to how you create it. It *can* do conditional - responses if you pass ``conditional_response=True`` when - instantiating (or set that attribute later). It can also do HEAD - and Range requests. +``response.charset`` + The ``charset`` parameter of the content-type, it also informs encoding in + ``response.text``. ``response.content_type_params`` is a dictionary of all + the parameters. + +``response.set_cookie(key, value, max_age=None, path='/', ...)`` + Set a cookie. The keyword arguments control the various cookie parameters. + The ``max_age`` argument is the length for the cookie to live in seconds + (you may also use a timedelta object). The ``Expires`` key will also be + set based on the value of ``max_age``. + +``response.delete_cookie(key, path='/', domain=None)`` + Delete a cookie from the client. This sets ``max_age`` to 0 and the cookie + value to ``''``. + +``response.cache_expires(seconds=0)`` + This makes the response cacheable for the given number of seconds, or if + ``seconds`` is ``0`` then the response is uncacheable (this also sets the + ``Expires`` header). + +``response(environ, start_response)`` + The response object is a WSGI application. As an application, it acts + according to how you create it. It *can* do conditional responses if you + pass ``conditional_response=True`` when instantiating (or set that + attribute later). It can also do HEAD and Range requests. .. index:: single: response headers @@ -449,12 +433,11 @@ Here are some highlights: Headers +++++++ -Like the request, most HTTP response headers are available as -properties. These are parsed, so you can do things like -``response.last_modified = os.path.getmtime(filename)``. +Like the request, most HTTP response headers are available as properties. These +are parsed, so you can do things like ``response.last_modified = +os.path.getmtime(filename)``. -The details are available in the `extracted Response documentation -`_. +The details are available in the :mod:`webob.response` API documentation. .. index:: single: response (creating) @@ -462,9 +445,9 @@ The details are available in the `extracted Response documentation Instantiating the Response ++++++++++++++++++++++++++ -Of course most of the time you just want to *make* a response. -Generally any attribute of the response can be passed in as a keyword -argument to the class; e.g.: +Of course most of the time you just want to *make* a response. Generally any +attribute of the response can be passed in as a keyword argument to the class, +e.g.: .. code-block:: python :linenos: @@ -474,9 +457,9 @@ argument to the class; e.g.: The status defaults to ``'200 OK'``. -The value of content_type defaults to -``webob.response.Response.default_content_type``; which is `text/html`. -You can subclass :class:`pyramid.response.Response` and set +The value of ``content_type`` defaults to +``webob.response.Response.default_content_type``, which is ``text/html``. You +can subclass :class:`pyramid.response.Response` and set ``default_content_type`` to override this behavior. .. index:: @@ -486,18 +469,16 @@ Exception Responses +++++++++++++++++++ To facilitate error responses like ``404 Not Found``, the module -:mod:`pyramid.httpexceptions` contains classes for each kind of error -response. These include boring, but appropriate error bodies. The -exceptions exposed by this module, when used under :app:`Pyramid`, should be -imported from the :mod:`pyramid.httpexceptions` module. This import location -contains subclasses and replacements that mirror those in the ``webob.exc`` -module. - -Each class is named ``pyramid.httpexceptions.HTTP*``, where ``*`` is the -reason for the error. For instance, -:class:`pyramid.httpexceptions.HTTPNotFound` subclasses -:class:`pyramid.response.Response`, so you can manipulate the instances in the same -way. A typical example is: +:mod:`pyramid.httpexceptions` contains classes for each kind of error response. +These include boring but appropriate error bodies. The exceptions exposed by +this module, when used under :app:`Pyramid`, should be imported from the +:mod:`pyramid.httpexceptions` module. This import location contains subclasses +and replacements that mirror those in the ``webob.exc`` module. + +Each class is named ``pyramid.httpexceptions.HTTP*``, where ``*`` is the reason +for the error. For instance, :class:`pyramid.httpexceptions.HTTPNotFound` +subclasses :class:`pyramid.response.Response`, so you can manipulate the +instances in the same way. A typical example is: .. code-block:: python :linenos: @@ -513,8 +494,6 @@ More Details ++++++++++++ More details about the response object API are available in the -:mod:`pyramid.response` documentation. More details about exception -responses are in the :mod:`pyramid.httpexceptions` API documentation. The -`WebOb documentation `_ is also -useful. - +:mod:`pyramid.response` documentation. More details about exception responses +are in the :mod:`pyramid.httpexceptions` API documentation. The `WebOb +documentation `_ is also useful. -- cgit v1.2.3 From 22f221099e785cb763e9659da029933ca9fc11e6 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Sun, 24 Jan 2016 01:10:13 -0800 Subject: Use proper syntax names in code samples to allow highlighting and avoid errors. See https://github.com/sphinx-doc/sphinx/issues/2264 --- docs/narr/webob.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/narr/webob.rst') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index f18cf1dfb..cfcf532bc 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -269,7 +269,7 @@ to a :app:`Pyramid` application: When such a request reaches a view in your application, the ``request.json_body`` attribute will be available in the view callable body. -.. code-block:: javascript +.. code-block:: python @view_config(renderer='string') def aview(request): -- cgit v1.2.3