summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
Diffstat (limited to 'docs')
-rw-r--r--docs/conventions.rst6
-rw-r--r--docs/narr/assets.rst430
-rw-r--r--docs/narr/commandline.rst38
-rw-r--r--docs/narr/configuration.rst92
-rw-r--r--docs/narr/firstapp.rst191
-rw-r--r--docs/narr/install.rst37
-rw-r--r--docs/narr/introduction.rst657
-rw-r--r--docs/narr/project-debug.pngbin106878 -> 202464 bytes
-rw-r--r--docs/narr/project-show-toolbar.pngbin0 -> 11050 bytes
-rw-r--r--docs/narr/project.pngbin91662 -> 133242 bytes
-rw-r--r--docs/narr/project.rst703
-rw-r--r--docs/narr/renderers.rst321
-rw-r--r--docs/narr/router.rst81
-rw-r--r--docs/narr/startup.rst108
-rw-r--r--docs/narr/templates.rst309
-rw-r--r--docs/narr/urldispatch.rst518
-rw-r--r--docs/narr/viewconfig.rst557
-rw-r--r--docs/narr/views.rst296
-rw-r--r--docs/tutorials/wiki2/basiclayout.rst2
19 files changed, 2140 insertions, 2206 deletions
diff --git a/docs/conventions.rst b/docs/conventions.rst
index 0492ab4fd..a9d2550bf 100644
--- a/docs/conventions.rst
+++ b/docs/conventions.rst
@@ -24,7 +24,7 @@ We present Python method names using the following style:
:meth:`pyramid.config.Configurator.add_view`
-We present Python class names, module names, attributes and global
+We present Python class names, module names, attributes, and global
variables using the following style:
:class:`pyramid.config.Configurator.registry`
@@ -105,10 +105,10 @@ It may look unusual, but it has advantages:
* It allows one to swap out the higher-level package ``foo`` for something
else that provides the similar API. An example would be swapping out
- one Database for another (e.g., graduating from SQLite to PostgreSQL).
+ one database for another (e.g., graduating from SQLite to PostgreSQL).
* Looks more neat in cases where a large number of objects get imported from
that package.
-* Adding/removing imported objects from the package is quicker and results
+* Adding or removing imported objects from the package is quicker and results
in simpler diffs.
diff --git a/docs/narr/assets.rst b/docs/narr/assets.rst
index 1beabe8de..4c0013298 100644
--- a/docs/narr/assets.rst
+++ b/docs/narr/assets.rst
@@ -7,8 +7,8 @@
Static Assets
=============
-An :term:`asset` is any file contained within a Python :term:`package` which
-is *not* a Python source code file. For example, each of the following is an
+An :term:`asset` is any file contained within a Python :term:`package` which is
+*not* a Python source code file. For example, each of the following is an
asset:
- a GIF image file contained within a Python package or contained within any
@@ -20,20 +20,20 @@ asset:
- a JavaScript source file contained within a Python package or contained
within any subdirectory of a Python package.
-- A directory within a package that does not have an ``__init__.py``
- in it (if it possessed an ``__init__.py`` it would *be* a package).
+- A directory within a package that does not have an ``__init__.py`` in it (if
+ it possessed an ``__init__.py`` it would *be* a package).
- a :term:`Chameleon` or :term:`Mako` template file contained within a Python
package.
The use of assets is quite common in most web development projects. For
example, when you create a :app:`Pyramid` application using one of the
-available scaffolds, as described in :ref:`creating_a_project`, the
-directory representing the application contains a Python :term:`package`.
-Within that Python package, there are directories full of files which are
-static assets. For example, there's a ``static`` directory which contains
-``.css``, ``.js``, and ``.gif`` files. These asset files are delivered when
-a user visits an application URL.
+available scaffolds, as described in :ref:`creating_a_project`, the directory
+representing the application contains a Python :term:`package`. Within that
+Python package, there are directories full of files which are static assets.
+For example, there's a ``static`` directory which contains ``.css``, ``.js``,
+and ``.gif`` files. These asset files are delivered when a user visits an
+application URL.
.. index::
single: asset specifications
@@ -45,10 +45,10 @@ Understanding Asset Specifications
Let's imagine you've created a :app:`Pyramid` application that uses a
:term:`Chameleon` ZPT template via the
-:func:`pyramid.renderers.render_to_response` API. For example, the
-application might address the asset using the :term:`asset specification`
-``myapp:templates/some_template.pt`` using that API within a ``views.py``
-file inside a ``myapp`` package:
+:func:`pyramid.renderers.render_to_response` API. For example, the application
+might address the asset using the :term:`asset specification`
+``myapp:templates/some_template.pt`` using that API within a ``views.py`` file
+inside a ``myapp`` package:
.. code-block:: python
:linenos:
@@ -66,23 +66,23 @@ two parts:
- The *asset name* (``templates/some_template.pt``), relative to the package
directory.
-The two parts are separated by the colon character.
+The two parts are separated by a colon ``:`` character.
-:app:`Pyramid` uses the Python :term:`pkg_resources` API to resolve the
-package name and asset name to an absolute (operating-system-specific) file
-name. It eventually passes this resolved absolute filesystem path to the
-Chameleon templating engine, which then uses it to load, parse, and execute
-the template file.
+:app:`Pyramid` uses the Python :term:`pkg_resources` API to resolve the package
+name and asset name to an absolute (operating system-specific) file name. It
+eventually passes this resolved absolute filesystem path to the Chameleon
+templating engine, which then uses it to load, parse, and execute the template
+file.
There is a second form of asset specification: a *relative* asset
specification. Instead of using an "absolute" asset specification which
includes the package name, in certain circumstances you can omit the package
name from the specification. For example, you might be able to use
``templates/mytemplate.pt`` instead of ``myapp:templates/some_template.pt``.
-Such asset specifications are usually relative to a "current package." The
+Such asset specifications are usually relative to a "current package". The
"current package" is usually the package which contains the code that *uses*
the asset specification. :app:`Pyramid` APIs which accept relative asset
-specifications typically describe what the asset is relative to in their
+specifications typically describe to what the asset is relative in their
individual documentation.
.. index::
@@ -96,17 +96,17 @@ Serving Static Assets
:app:`Pyramid` makes it possible to serve up static asset files from a
directory on a filesystem to an application user's browser. Use the
-:meth:`pyramid.config.Configurator.add_static_view` to instruct
-:app:`Pyramid` to serve static assets such as JavaScript and CSS files. This
-mechanism makes a directory of static files available at a name relative to
-the application root URL, e.g. ``/static`` or as an external URL.
+:meth:`pyramid.config.Configurator.add_static_view` to instruct :app:`Pyramid`
+to serve static assets, such as JavaScript and CSS files. This mechanism makes
+a directory of static files available at a name relative to the application
+root URL, e.g., ``/static``, or as an external URL.
.. note::
- :meth:`~pyramid.config.Configurator.add_static_view` cannot serve a
- single file, nor can it serve a directory of static files directly
- relative to the root URL of a :app:`Pyramid` application. For these
- features, see :ref:`advanced_static`.
+ :meth:`~pyramid.config.Configurator.add_static_view` cannot serve a single
+ file, nor can it serve a directory of static files directly relative to the
+ root URL of a :app:`Pyramid` application. For these features, see
+ :ref:`advanced_static`.
Here's an example of a use of
:meth:`~pyramid.config.Configurator.add_static_view` that will serve files up
@@ -121,11 +121,11 @@ from the ``/var/www/static`` directory of the computer which runs the
The ``name`` represents a URL *prefix*. In order for files that live in the
``path`` directory to be served, a URL that requests one of them must begin
-with that prefix. In the example above, ``name`` is ``static``, and ``path``
-is ``/var/www/static``. In English, this means that you wish to serve the
-files that live in ``/var/www/static`` as sub-URLs of the ``/static`` URL
-prefix. Therefore, the file ``/var/www/static/foo.css`` will be returned
-when the user visits your application's URL ``/static/foo.css``.
+with that prefix. In the example above, ``name`` is ``static`` and ``path`` is
+``/var/www/static``. In English this means that you wish to serve the files
+that live in ``/var/www/static`` as sub-URLs of the ``/static`` URL prefix.
+Therefore, the file ``/var/www/static/foo.css`` will be returned when the user
+visits your application's URL ``/static/foo.css``.
A static directory named at ``path`` may contain subdirectories recursively,
and any subdirectories may hold files; these will be resolved by the static
@@ -134,16 +134,16 @@ view for each particular type of file is dependent upon its file extension.
By default, all files made available via
:meth:`~pyramid.config.Configurator.add_static_view` are accessible by
-completely anonymous users. Simple authorization can be required, however.
-To protect a set of static files using a permission, in addition to passing
-the required ``name`` and ``path`` arguments, also pass the ``permission``
-keyword argument to :meth:`~pyramid.config.Configurator.add_static_view`.
-The value of the ``permission`` argument represents the :term:`permission`
-that the user must have relative to the current :term:`context` when the
-static view is invoked. A user will be required to possess this permission
-to view any of the files represented by ``path`` of the static view. If your
-static assets must be protected by a more complex authorization scheme,
-see :ref:`advanced_static`.
+completely anonymous users. Simple authorization can be required, however. To
+protect a set of static files using a permission, in addition to passing the
+required ``name`` and ``path`` arguments, also pass the ``permission`` keyword
+argument to :meth:`~pyramid.config.Configurator.add_static_view`. The value of
+the ``permission`` argument represents the :term:`permission` that the user
+must have relative to the current :term:`context` when the static view is
+invoked. A user will be required to possess this permission to view any of the
+files represented by ``path`` of the static view. If your static assets must
+be protected by a more complex authorization scheme, see
+:ref:`advanced_static`.
Here's another example that uses an :term:`asset specification` instead of an
absolute path as the ``path`` argument. To convince
@@ -163,14 +163,14 @@ may be a fully qualified :term:`asset specification` or an *absolute path*.
Instead of representing a URL prefix, the ``name`` argument of a call to
:meth:`~pyramid.config.Configurator.add_static_view` can alternately be a
-*URL*. Each of examples we've seen so far have shown usage of the ``name``
-argument as a URL prefix. However, when ``name`` is a *URL*, static assets
-can be served from an external webserver. In this mode, the ``name`` is used
-as the URL prefix when generating a URL using
+*URL*. Each of the examples we've seen so far have shown usage of the ``name``
+argument as a URL prefix. However, when ``name`` is a *URL*, static assets can
+be served from an external webserver. In this mode, the ``name`` is used as
+the URL prefix when generating a URL using
:meth:`pyramid.request.Request.static_url`.
-For example, :meth:`~pyramid.config.Configurator.add_static_view` may
-be fed a ``name`` argument which is ``http://example.com/images``:
+For example, :meth:`~pyramid.config.Configurator.add_static_view` may be fed a
+``name`` argument which is ``http://example.com/images``:
.. code-block:: python
:linenos:
@@ -179,15 +179,15 @@ be fed a ``name`` argument which is ``http://example.com/images``:
config.add_static_view(name='http://example.com/images',
path='mypackage:images')
-Because :meth:`~pyramid.config.Configurator.add_static_view` is provided with
-a ``name`` argument that is the URL ``http://example.com/images``, subsequent
-calls to :meth:`~pyramid.request.Request.static_url` with paths that start
-with the ``path`` argument passed to
+Because :meth:`~pyramid.config.Configurator.add_static_view` is provided with a
+``name`` argument that is the URL ``http://example.com/images``, subsequent
+calls to :meth:`~pyramid.request.Request.static_url` with paths that start with
+the ``path`` argument passed to
:meth:`~pyramid.config.Configurator.add_static_view` will generate a URL
-something like ``http://example.com/images/logo.png``. The external
-webserver listening on ``example.com`` must be itself configured to respond
-properly to such a request. The :meth:`~pyramid.request.Request.static_url`
-API is discussed in more detail later in this chapter.
+something like ``http://example.com/images/logo.png``. The external webserver
+listening on ``example.com`` must be itself configured to respond properly to
+such a request. The :meth:`~pyramid.request.Request.static_url` API is
+discussed in more detail later in this chapter.
.. index::
single: generating static asset urls
@@ -199,11 +199,11 @@ API is discussed in more detail later in this chapter.
Generating Static Asset URLs
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-When a :meth:`~pyramid.config.Configurator.add_static_view` method is used to
+When an :meth:`~pyramid.config.Configurator.add_static_view` method is used to
register a static asset directory, a special helper API named
:meth:`pyramid.request.Request.static_url` can be used to generate the
-appropriate URL for an asset that lives in one of the directories named by
-the static registration ``path`` attribute.
+appropriate URL for an asset that lives in one of the directories named by the
+static registration ``path`` attribute.
For example, let's assume you create a set of static declarations like so:
@@ -213,12 +213,12 @@ For example, let's assume you create a set of static declarations like so:
config.add_static_view(name='static1', path='mypackage:assets/1')
config.add_static_view(name='static2', path='mypackage:assets/2')
-These declarations create URL-accessible directories which have URLs that
-begin with ``/static1`` and ``/static2``, respectively. The assets in the
+These declarations create URL-accessible directories which have URLs that begin
+with ``/static1`` and ``/static2``, respectively. The assets in the
``assets/1`` directory of the ``mypackage`` package are consulted when a user
-visits a URL which begins with ``/static1``, and the assets in the
-``assets/2`` directory of the ``mypackage`` package are consulted when a user
-visits a URL which begins with ``/static2``.
+visits a URL which begins with ``/static1``, and the assets in the ``assets/2``
+directory of the ``mypackage`` package are consulted when a user visits a URL
+which begins with ``/static2``.
You needn't generate the URLs to static assets "by hand" in such a
configuration. Instead, use the :meth:`~pyramid.request.Request.static_url`
@@ -238,8 +238,8 @@ API to generate them for you. For example:
If the request "application URL" of the running system is
``http://example.com``, the ``css_url`` generated above would be:
-``http://example.com/static1/foo.css``. The ``js_url`` generated
-above would be ``http://example.com/static2/foo.js``.
+``http://example.com/static1/foo.css``. The ``js_url`` generated above would
+be ``http://example.com/static2/foo.js``.
One benefit of using the :meth:`~pyramid.request.Request.static_url` function
rather than constructing static URLs "by hand" is that if you need to change
@@ -249,10 +249,9 @@ resolve properly after the rename.
URLs may also be generated by :meth:`~pyramid.request.Request.static_url` to
static assets that live *outside* the :app:`Pyramid` application. This will
happen when the :meth:`~pyramid.config.Configurator.add_static_view` API
-associated with the path fed to :meth:`~pyramid.request.Request.static_url`
-is a *URL* instead of a view name. For example, the ``name`` argument may be
-``http://example.com`` while the ``path`` given may be
-``mypackage:images``:
+associated with the path fed to :meth:`~pyramid.request.Request.static_url` is
+a *URL* instead of a view name. For example, the ``name`` argument may be
+``http://example.com`` while the ``path`` given may be ``mypackage:images``:
.. code-block:: python
:linenos:
@@ -260,8 +259,8 @@ is a *URL* instead of a view name. For example, the ``name`` argument may be
config.add_static_view(name='http://example.com/images',
path='mypackage:images')
-Under such a configuration, the URL generated by ``static_url`` for
-assets which begin with ``mypackage:images`` will be prefixed with
+Under such a configuration, the URL generated by ``static_url`` for assets
+which begin with ``mypackage:images`` will be prefixed with
``http://example.com/images``:
.. code-block:: python
@@ -271,16 +270,16 @@ assets which begin with ``mypackage:images`` will be prefixed with
# -> http://example.com/images/logo.png
Using :meth:`~pyramid.request.Request.static_url` in conjunction with a
-:meth:`~pyramid.config.Configurator.add_static_view` makes it possible
-to put static media on a separate webserver during production (if the
-``name`` argument to :meth:`~pyramid.config.Configurator.add_static_view` is
-a URL), while keeping static media package-internal and served by the
-development webserver during development (if the ``name`` argument to
+:meth:`~pyramid.config.Configurator.add_static_view` makes it possible to put
+static media on a separate webserver during production (if the ``name``
+argument to :meth:`~pyramid.config.Configurator.add_static_view` is a URL),
+while keeping static media package-internal and served by the development
+webserver during development (if the ``name`` argument to
:meth:`~pyramid.config.Configurator.add_static_view` is a URL prefix).
For example, we may define a :ref:`custom setting <adding_a_custom_setting>`
-named ``media_location`` which we can set to an external URL in production
-when our assets are hosted on a CDN.
+named ``media_location`` which we can set to an external URL in production when
+our assets are hosted on a CDN.
.. code-block:: python
:linenos:
@@ -305,18 +304,19 @@ It is also possible to serve assets that live outside of the source by
referring to an absolute path on the filesystem. There are two ways to
accomplish this.
-First, :meth:`~pyramid.config.Configurator.add_static_view`
-supports taking an absolute path directly instead of an asset spec. This works
-as expected, looking in the file or folder of files and serving them up at
-some URL within your application or externally. Unfortunately, this technique
-has a drawback that it is not possible to use the
-:meth:`~pyramid.request.Request.static_url` method to generate URLs, since it
-works based on an asset spec.
+First, :meth:`~pyramid.config.Configurator.add_static_view` supports taking an
+absolute path directly instead of an asset spec. This works as expected,
+looking in the file or folder of files and serving them up at some URL within
+your application or externally. Unfortunately, this technique has a drawback in
+that it is not possible to use the :meth:`~pyramid.request.Request.static_url`
+method to generate URLs, since it works based on an asset specification.
-The second approach, available in Pyramid 1.6+, uses the asset overriding
-APIs described in the :ref:`overriding_assets_section` section. It is then
-possible to configure a "dummy" package which then serves its file or folder
-from an absolute path.
+.. versionadded:: 1.6
+
+The second approach, available in Pyramid 1.6+, uses the asset overriding APIs
+described in the :ref:`overriding_assets_section` section. It is then possible
+to configure a "dummy" package which then serves its file or folder from an
+absolute path.
.. code-block:: python
@@ -325,13 +325,13 @@ from an absolute path.
override_with='/abs/path/to/images/')
From this configuration it is now possible to use
-:meth:`~pyramid.request.Request.static_url` to generate URLs to the data
-in the folder by doing something like
+:meth:`~pyramid.request.Request.static_url` to generate URLs to the data in the
+folder by doing something like
``request.static_url('myapp:static_images/foo.png')``. While it is not
necessary that the ``static_images`` file or folder actually exist in the
-``myapp`` package, it is important that the ``myapp`` portion points to a
-valid package. If the folder does exist then the overriden folder is given
-priority if the file's name exists in both locations.
+``myapp`` package, it is important that the ``myapp`` portion points to a valid
+package. If the folder does exist, then the overriden folder is given priority,
+if the file's name exists in both locations.
.. index::
single: Cache Busting
@@ -343,31 +343,30 @@ Cache Busting
.. versionadded:: 1.6
-In order to maximize performance of a web application, you generally want to
+In order to maximize performance of a web application, you generally want to
limit the number of times a particular client requests the same static asset.
-Ideally a client would cache a particular static asset "forever", requiring
-it to be sent to the client a single time. The HTTP protocol allows you to
-send headers with an HTTP response that can instruct a client to cache a
-particular asset for an amount of time. As long as the client has a copy of
-the asset in its cache and that cache hasn't expired, the client will use the
-cached copy rather than request a new copy from the server. The drawback to
-sending cache headers to the client for a static asset is that at some point
-the static asset may change, and then you'll want the client to load a new copy
-of the asset. Under normal circumstances you'd just need to wait for the
-client's cached copy to expire before they get the new version of the static
-resource.
-
-A commonly used workaround to this problem is a technique known as "cache
-busting". Cache busting schemes generally involve generating a URL for a
+Ideally a client would cache a particular static asset "forever", requiring it
+to be sent to the client a single time. The HTTP protocol allows you to send
+headers with an HTTP response that can instruct a client to cache a particular
+asset for an amount of time. As long as the client has a copy of the asset in
+its cache and that cache hasn't expired, the client will use the cached copy
+rather than request a new copy from the server. The drawback to sending cache
+headers to the client for a static asset is that at some point the static asset
+may change, and then you'll want the client to load a new copy of the asset.
+Under normal circumstances you'd just need to wait for the client's cached copy
+to expire before they get the new version of the static resource.
+
+A commonly used workaround to this problem is a technique known as "cache
+busting". Cache busting schemes generally involve generating a URL for a
static asset that changes when the static asset changes. This way headers can
be sent along with the static asset instructing the client to cache the asset
for a very long time. When a static asset is changed, the URL used to refer to
-it in a web page also changes, so the client sees it as a new resource and
-requests a copy, regardless of any caching policy set for the resource's old
+it in a web page also changes, so the client sees it as a new resource and
+requests the asset, regardless of any caching policy set for the resource's old
URL.
-:app:`Pyramid` can be configured to produce cache busting URLs for static
-assets by passing the optional argument, ``cachebust`` to
+:app:`Pyramid` can be configured to produce cache busting URLs for static
+assets by passing the optional argument, ``cachebust`` to
:meth:`~pyramid.config.Configurator.add_static_view`:
.. code-block:: python
@@ -377,7 +376,7 @@ assets by passing the optional argument, ``cachebust`` to
config.add_static_view(name='static', path='mypackage:folder/static',
cachebust=True)
-Setting the ``cachebust`` argument instructs :app:`Pyramid` to use a cache
+Setting the ``cachebust`` argument instructs :app:`Pyramid` to use a cache
busting scheme which adds the md5 checksum for a static asset as a path segment
in the asset's URL:
@@ -385,7 +384,7 @@ in the asset's URL:
:linenos:
js_url = request.static_url('mypackage:folder/static/js/myapp.js')
- # Returns: 'http://www.example.com/static/c9658b3c0a314a1ca21e5988e662a09e/js/myapp.js`
+ # Returns: 'http://www.example.com/static/c9658b3c0a314a1ca21e5988e662a09e/js/myapp.js'
When the asset changes, so will its md5 checksum, and therefore so will its
URL. Supplying the ``cachebust`` argument also causes the static view to set
@@ -394,17 +393,17 @@ headers instructing clients to cache the asset for ten years, unless the
.. note::
- md5 checksums are cached in RAM so if you change a static resource without
+ md5 checksums are cached in RAM, so if you change a static resource without
restarting your application, you may still generate URLs with a stale md5
- checksum.
+ checksum.
Disabling the Cache Buster
~~~~~~~~~~~~~~~~~~~~~~~~~~
-It can be useful in some situations (e.g. development) to globally disable all
+It can be useful in some situations (e.g., development) to globally disable all
configured cache busters without changing calls to
-:meth:`~pyramid.config.Configurator.add_static_view`. To do this set the
-``PYRAMID_PREVENT_CACHEBUST`` environment variable or the
+:meth:`~pyramid.config.Configurator.add_static_view`. To do this set the
+``PYRAMID_PREVENT_CACHEBUST`` environment variable or the
``pyramid.prevent_cachebust`` configuration value to a true value.
Customizing the Cache Buster
@@ -420,8 +419,8 @@ Revisiting from the previous section:
cachebust=True)
Setting ``cachebust`` to ``True`` instructs :app:`Pyramid` to use a default
-cache busting implementation that should work for many situations. The
-``cachebust`` may be set to any object that implements the interface,
+cache busting implementation that should work for many situations. The
+``cachebust`` may be set to any object that implements the interface
:class:`~pyramid.interfaces.ICacheBuster`. The above configuration is exactly
equivalent to:
@@ -440,7 +439,7 @@ checksum token in the path portion of the asset's URL,
:class:`~pyramid.static.QueryStringMd5CacheBuster`, which adds an md5 checksum
token to the query string of the asset's URL, and
:class:`~pyramid.static.QueryStringConstantCacheBuster`, which adds an
-arbitrary token you provide to the query string of the asset's URL.
+arbitrary token you provide to the query string of the asset's URL.
In order to implement your own cache buster, you can write your own class from
scratch which implements the :class:`~pyramid.interfaces.ICacheBuster`
@@ -461,9 +460,9 @@ the hash of the currently checked out code:
class GitCacheBuster(PathSegmentCacheBuster):
"""
- Assuming your code is installed as a Git checkout, as opposed to as an
- egg from an egg repository like PYPI, you can use this cachebuster to
- get the current commit's SHA1 to use as the cache bust token.
+ Assuming your code is installed as a Git checkout, as opposed to an egg
+ from an egg repository like PYPI, you can use this cachebuster to get
+ the current commit's SHA1 to use as the cache bust token.
"""
def __init__(self):
here = os.path.dirname(os.path.abspath(__file__))
@@ -477,25 +476,25 @@ the hash of the currently checked out code:
Choosing a Cache Buster
~~~~~~~~~~~~~~~~~~~~~~~
-The default cache buster implementation,
-:class:`~pyramid.static.PathSegmentMd5CacheBuster`, works very well assuming
+The default cache buster implementation,
+:class:`~pyramid.static.PathSegmentMd5CacheBuster`, works very well assuming
that you're using :app:`Pyramid` to serve your static assets. The md5 checksum
-is fine grained enough that browsers should only request new versions of
-specific assets that have changed. Many caching HTTP proxies will fail to
-cache a resource if the URL contains a query string. In general, therefore,
-you should prefer a cache busting strategy which modifies the path segment to
-a strategy which adds a query string.
+is fine grained enough that browsers should only request new versions of
+specific assets that have changed. Many caching HTTP proxies will fail to
+cache a resource if the URL contains a query string. In general, therefore,
+you should prefer a cache busting strategy which modifies the path segment to a
+strategy which adds a query string.
It is possible, however, that your static assets are being served by another
web server or externally on a CDN. In these cases modifying the path segment
for a static asset URL would cause the external service to fail to find the
-asset, causing your customer to get a 404. In these cases you would need to
-fall back to a cache buster which adds a query string. It is even possible
+asset, causing your customer to get a 404. In these cases you would need to
+fall back to a cache buster which adds a query string. It is even possible
that there isn't a copy of your static assets available to the :app:`Pyramid`
application, so a cache busting implementation that generates md5 checksums
-would fail since it can't access the assets. In such a case,
-:class:`~pyramid.static.QueryStringConstantCacheBuster` is a reasonable
-fallback. The following code would set up a cachebuster that just uses the
+would fail since it can't access the assets. In such a case,
+:class:`~pyramid.static.QueryStringConstantCacheBuster` is a reasonable
+fallback. The following code would set up a cachebuster that just uses the
time at start up as a cachebust token:
.. code-block:: python
@@ -516,10 +515,10 @@ CSS and JavaScript source and cache busting
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Often one needs to refer to images and other static assets inside CSS and
-JavaScript files. If cache busting is active, the final static asset URL is
-not available until the static assets have been assembled. These URLs cannot
-be handwritten. Thus, when having static asset references in CSS and
-JavaScript, one needs to perform one of the following tasks.
+JavaScript files. If cache busting is active, the final static asset URL is not
+available until the static assets have been assembled. These URLs cannot be
+handwritten. Thus, when having static asset references in CSS and JavaScript,
+one needs to perform one of the following tasks.
* Process the files by using a precompiler which rewrites URLs to their final
cache busted form.
@@ -536,8 +535,8 @@ packages.
Relative cache busted URLs in CSS
+++++++++++++++++++++++++++++++++
-Consider a CSS file ``/static/theme/css/site.css`` which contains the
-following CSS code.
+Consider a CSS file ``/static/theme/css/site.css`` which contains the following
+CSS code.
.. code-block:: css
@@ -572,8 +571,8 @@ The browser would interpret this as having the CSS file hash in URL::
The downside of this approach is that if the background image changes, one
needs to bump the CSS file. The CSS file hash change signals the caches that
the relative URL to the image in the CSS has been changed. When updating CSS
-and related image assets, updates usually happen hand in hand, so this does
-not add extra effort to theming workflow.
+and related image assets, updates usually happen hand in hand, so this does not
+add extra effort to theming workflow.
Passing cache busted URLs to JavaScript
+++++++++++++++++++++++++++++++++++++++
@@ -593,7 +592,7 @@ relevant page.
"{{ '/theme/img/background.jpg'|static_url() }}";
</script>
-Then in your main ``site.js`` file put the following code.
+Then in your main ``site.js`` file, put the following code.
.. code-block:: javascript
@@ -606,13 +605,13 @@ Advanced: Serving Static Assets Using a View Callable
For more flexibility, static assets can be served by a :term:`view callable`
which you register manually. For example, if you're using :term:`URL
-dispatch`, you may want static assets to only be available as a fallback if
-no previous route matches. Alternately, you might like to serve a particular
+dispatch`, you may want static assets to only be available as a fallback if no
+previous route matches. Alternatively, you might like to serve a particular
static asset manually, because its download requires authentication.
-Note that you cannot use the :meth:`~pyramid.request.Request.static_url` API
-to generate URLs against assets made accessible by registering a custom
-static view.
+Note that you cannot use the :meth:`~pyramid.request.Request.static_url` API to
+generate URLs against assets made accessible by registering a custom static
+view.
Root-Relative Custom Static View (URL Dispatch Only)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -626,19 +625,19 @@ its behavior is almost exactly the same once it's configured.
.. warning::
The following example *will not work* for applications that use
- :term:`traversal`, it will only work if you use :term:`URL dispatch`
+ :term:`traversal`; it will only work if you use :term:`URL dispatch`
exclusively. The root-relative route we'll be registering will always be
matched before traversal takes place, subverting any views registered via
``add_view`` (at least those without a ``route_name``). A
:class:`~pyramid.static.static_view` static view cannot be made
- root-relative when you use traversal unless it's registered as a
- :term:`Not Found View`.
+ root-relative when you use traversal unless it's registered as a :term:`Not
+ Found View`.
To serve files within a directory located on your filesystem at
``/path/to/static/dir`` as the result of a "catchall" route hanging from the
root that exists at the end of your routing table, create an instance of the
-:class:`~pyramid.static.static_view` class inside a ``static.py`` file in
-your application root as below.
+:class:`~pyramid.static.static_view` class inside a ``static.py`` file in your
+application root as below.
.. code-block:: python
:linenos:
@@ -648,10 +647,10 @@ your application root as below.
.. note::
- For better cross-system flexibility, use an :term:`asset
- specification` as the argument to :class:`~pyramid.static.static_view`
- instead of a physical absolute filesystem path, e.g. ``mypackage:static``
- instead of ``/path/to/mypackage/static``.
+ For better cross-system flexibility, use an :term:`asset specification` as
+ the argument to :class:`~pyramid.static.static_view` instead of a physical
+ absolute filesystem path, e.g., ``mypackage:static``, instead of
+ ``/path/to/mypackage/static``.
Subsequently, you may wire the files that are served by this view up to be
accessible as ``/<filename>`` using a configuration method in your
@@ -670,11 +669,11 @@ The special name ``*subpath`` above is used by the
:class:`~pyramid.static.static_view` view callable to signify the path of the
file relative to the directory you're serving.
-Registering A View Callable to Serve a "Static" Asset
+Registering a View Callable to Serve a "Static" Asset
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-You can register a simple view callable to serve a single static asset. To
-do so, do things "by hand". First define the view callable.
+You can register a simple view callable to serve a single static asset. To do
+so, do things "by hand". First define the view callable.
.. code-block:: python
:linenos:
@@ -687,17 +686,16 @@ do so, do things "by hand". First define the view callable.
icon = os.path.join(here, 'static', 'favicon.ico')
return FileResponse(icon, request=request)
-The above bit of code within ``favicon_view`` computes "here", which is a
-path relative to the Python file in which the function is defined. It then
-creates a :class:`pyramid.response.FileResponse` using the file path as the
-response's ``path`` argument and the request as the response's ``request``
-argument. :class:`pyramid.response.FileResponse` will serve the file as
-quickly as possible when it's used this way. It makes sure to set the right
-content length and content_type too based on the file extension of the file
-you pass.
+The above bit of code within ``favicon_view`` computes "here", which is a path
+relative to the Python file in which the function is defined. It then creates
+a :class:`pyramid.response.FileResponse` using the file path as the response's
+``path`` argument and the request as the response's ``request`` argument.
+:class:`pyramid.response.FileResponse` will serve the file as quickly as
+possible when it's used this way. It makes sure to set the right content
+length and content_type, too, based on the file extension of the file you pass.
-You might register such a view via configuration as a view callable that
-should be called as the result of a traversal:
+You might register such a view via configuration as a view callable that should
+be called as the result of a traversal:
.. code-block:: python
:linenos:
@@ -730,13 +728,12 @@ It can often be useful to override specific assets from "outside" a given
:app:`Pyramid` application more or less unchanged. However, some specific
template file owned by the application might have inappropriate HTML, or some
static asset (such as a logo file or some CSS file) might not be appropriate.
-You *could* just fork the application entirely, but it's often more
-convenient to just override the assets that are inappropriate and reuse the
-application "as is". This is particularly true when you reuse some "core"
-application over and over again for some set of customers (such as a CMS
-application, or some bug tracking application), and you want to make
-arbitrary visual modifications to a particular application deployment without
-forking the underlying code.
+You *could* just fork the application entirely, but it's often more convenient
+to just override the assets that are inappropriate and reuse the application
+"as is". This is particularly true when you reuse some "core" application over
+and over again for some set of customers (such as a CMS application, or some
+bug tracking application), and you want to make arbitrary visual modifications
+to a particular application deployment without forking the underlying code.
To this end, :app:`Pyramid` contains a feature that makes it possible to
"override" one asset with one or more other assets. In support of this
@@ -754,8 +751,8 @@ feature, a :term:`Configurator` API exists named
- A directory of static files served up by an instance of the
``pyramid.static.static_view`` helper class.
-- Any other asset (or set of assets) addressed by code that uses the
- setuptools :term:`pkg_resources` API.
+- Any other asset (or set of assets) addressed by code that uses the setuptools
+ :term:`pkg_resources` API.
.. index::
single: override_asset
@@ -765,8 +762,8 @@ feature, a :term:`Configurator` API exists named
The ``override_asset`` API
~~~~~~~~~~~~~~~~~~~~~~~~~~
-An individual call to :meth:`~pyramid.config.Configurator.override_asset`
-can override a single asset. For example:
+An individual call to :meth:`~pyramid.config.Configurator.override_asset` can
+override a single asset. For example:
.. code-block:: python
:linenos:
@@ -776,11 +773,11 @@ can override a single asset. For example:
override_with='another.package:othertemplates/anothertemplate.pt')
The string value passed to both ``to_override`` and ``override_with`` sent to
-the ``override_asset`` API is called an :term:`asset specification`. The
-colon separator in a specification separates the *package name* from the
-*asset name*. The colon and the following asset name are optional. If they
-are not specified, the override attempts to resolve every lookup into a
-package from the directory of another package. For example:
+the ``override_asset`` API is called an :term:`asset specification`. The colon
+separator in a specification separates the *package name* from the *asset
+name*. The colon and the following asset name are optional. If they are not
+specified, the override attempts to resolve every lookup into a package from
+the directory of another package. For example:
.. code-block:: python
:linenos:
@@ -796,27 +793,25 @@ Individual subdirectories within a package can also be overridden:
config.override_asset(to_override='some.package:templates/',
override_with='another.package:othertemplates/')
-
-If you wish to override a directory with another directory, you *must*
-make sure to attach the slash to the end of both the ``to_override``
-specification and the ``override_with`` specification. If you fail to
-attach a slash to the end of a specification that points to a directory,
-you will get unexpected results.
+If you wish to override a directory with another directory, you *must* make
+sure to attach the slash to the end of both the ``to_override`` specification
+and the ``override_with`` specification. If you fail to attach a slash to the
+end of a specification that points to a directory, you will get unexpected
+results.
You cannot override a directory specification with a file specification, and
-vice versa: a startup error will occur if you try. You cannot override an
-asset with itself: a startup error will occur if you try.
+vice versa; a startup error will occur if you try. You cannot override an
+asset with itself; a startup error will occur if you try.
Only individual *package* assets may be overridden. Overrides will not
-traverse through subpackages within an overridden package. This means that
-if you want to override assets for both ``some.package:templates``, and
+traverse through subpackages within an overridden package. This means that if
+you want to override assets for both ``some.package:templates``, and
``some.package.views:templates``, you will need to register two overrides.
-The package name in a specification may start with a dot, meaning that
-the package is relative to the package in which the configuration
-construction file resides (or the ``package`` argument to the
-:class:`~pyramid.config.Configurator` class construction).
-For example:
+The package name in a specification may start with a dot, meaning that the
+package is relative to the package in which the configuration construction file
+resides (or the ``package`` argument to the
+:class:`~pyramid.config.Configurator` class construction). For example:
.. code-block:: python
:linenos:
@@ -824,18 +819,19 @@ For example:
config.override_asset(to_override='.subpackage:templates/',
override_with='another.package:templates/')
-Multiple calls to ``override_asset`` which name a shared ``to_override`` but
-a different ``override_with`` specification can be "stacked" to form a search
-path. The first asset that exists in the search path will be used; if no
-asset exists in the override path, the original asset is used.
+Multiple calls to ``override_asset`` which name a shared ``to_override`` but a
+different ``override_with`` specification can be "stacked" to form a search
+path. The first asset that exists in the search path will be used; if no asset
+exists in the override path, the original asset is used.
Asset overrides can actually override assets other than templates and static
files. Any software which uses the
:func:`pkg_resources.get_resource_filename`,
-:func:`pkg_resources.get_resource_stream` or
+:func:`pkg_resources.get_resource_stream`, or
:func:`pkg_resources.get_resource_string` APIs will obtain an overridden file
when an override is used.
-As of Pyramid 1.6, it is also possible to override an asset by supplying an
-absolute path to a file or directory. This may be useful if the assets are
-not distributed as part of a Python package.
+.. versionadded:: 1.6
+ As of Pyramid 1.6, it is also possible to override an asset by supplying an
+ absolute path to a file or directory. This may be useful if the assets are
+ not distributed as part of a Python package.
diff --git a/docs/narr/commandline.rst b/docs/narr/commandline.rst
index 1fe2d9278..cb0c914d7 100644
--- a/docs/narr/commandline.rst
+++ b/docs/narr/commandline.rst
@@ -245,7 +245,7 @@ exposed, and the request is configured to generate urls from the host
.. code-block:: text
$ $VENV/bin/pshell starter/development.ini
- Python 2.6.5 (r265:79063, Apr 29 2010, 00:31:32)
+ Python 2.6.5 (r265:79063, Apr 29 2010, 00:31:32)
[GCC 4.4.3] on linux2
Type "help" for more information.
@@ -278,16 +278,46 @@ IPython or bpython
If you have `IPython <http://en.wikipedia.org/wiki/IPython>`_ and/or
`bpython <http://bpython-interpreter.org/>`_ in
-the interpreter you use to invoke the ``pshell`` command, ``pshell`` will
+the interpreter you use to invoke the ``pshell`` command, ``pshell`` will
autodiscover and use the first one found, in this order:
-IPython, bpython, standard Python interpreter. However you could
-specifically invoke one of your choice with the ``-p choice`` or
+IPython, bpython, standard Python interpreter. However you could
+specifically invoke one of your choice with the ``-p choice`` or
``--python-shell choice`` option.
.. code-block:: text
$ $VENV/bin/pshell -p ipython | bpython | python development.ini#MyProject
+Alternative Shells
+~~~~~~~~~~~~~~~~~~
+If you want to use a shell that isn't supported out of the box you can introduce
+a new shell by registering an entrypoint in your setup.py:
+
+.. code-block:: python
+
+ setup(
+ entry_points = """\
+ [pyramid.pshell]
+ myshell=my_app.ptpython_shell_factory
+ """
+ )
+
+and then your shell factory should return a function that accepts two arguments,
+``env`` and ``help``, this would look like this:
+
+.. code-block:: python
+
+ def ptpython_shell_factory():
+ from ptpython.repl import embed
+ def PTPShell(banner, **kwargs):
+ print(banner)
+ return embed(**kwargs)
+
+ def shell(env, help):
+ PTPShell(banner=help, locals=env)
+
+ return shell
+
.. index::
pair: routes; printing
single: proutes
diff --git a/docs/narr/configuration.rst b/docs/narr/configuration.rst
index f7fa94daf..cde166b21 100644
--- a/docs/narr/configuration.rst
+++ b/docs/narr/configuration.rst
@@ -3,27 +3,26 @@
.. _configuration_narr:
-Application Configuration
+Application Configuration
=========================
Most people already understand "configuration" as settings that influence the
-operation of an application. For instance, it's easy to think of the values
-in a ``.ini`` file parsed at application startup time as "configuration".
-However, if you're reasonably open-minded, it's easy to think of *code* as
-configuration too. Since Pyramid, like most other web application platforms,
-is a *framework*, it calls into code that you write (as opposed to a
-*library*, which is code that exists purely for you to call). The act of
-plugging application code that you've written into :app:`Pyramid` is also
-referred to within this documentation as "configuration"; you are configuring
+operation of an application. For instance, it's easy to think of the values in
+a ``.ini`` file parsed at application startup time as "configuration". However,
+if you're reasonably open-minded, it's easy to think of *code* as configuration
+too. Since Pyramid, like most other web application platforms, is a
+*framework*, it calls into code that you write (as opposed to a *library*,
+which is code that exists purely for you to call). The act of plugging
+application code that you've written into :app:`Pyramid` is also referred to
+within this documentation as "configuration"; you are configuring
:app:`Pyramid` to call the code that makes up your application.
.. seealso::
For information on ``.ini`` files for Pyramid applications see the
:ref:`startup_chapter` chapter.
-There are two ways to configure a :app:`Pyramid` application:
-:term:`imperative configuration` and :term:`declarative configuration`. Both
-are described below.
+There are two ways to configure a :app:`Pyramid` application: :term:`imperative
+configuration` and :term:`declarative configuration`. Both are described below.
.. index::
single: imperative configuration
@@ -33,9 +32,9 @@ are described below.
Imperative Configuration
------------------------
-"Imperative configuration" just means configuration done by Python
-statements, one after the next. Here's one of the simplest :app:`Pyramid`
-applications, configured imperatively:
+"Imperative configuration" just means configuration done by Python statements,
+one after the next. Here's one of the simplest :app:`Pyramid` applications,
+configured imperatively:
.. code-block:: python
:linenos:
@@ -57,9 +56,9 @@ applications, configured imperatively:
We won't talk much about what this application does yet. Just note that the
"configuration' statements take place underneath the ``if __name__ ==
'__main__':`` stanza in the form of method calls on a :term:`Configurator`
-object (e.g. ``config.add_view(...)``). These statements take place one
-after the other, and are executed in order, so the full power of Python,
-including conditionals, can be employed in this mode of configuration.
+object (e.g., ``config.add_view(...)``). These statements take place one after
+the other, and are executed in order, so the full power of Python, including
+conditionals, can be employed in this mode of configuration.
.. index::
single: view_config
@@ -72,13 +71,13 @@ Declarative Configuration
-------------------------
It's sometimes painful to have all configuration done by imperative code,
-because often the code for a single application may live in many files. If
-the configuration is centralized in one place, you'll need to have at least
-two files open at once to see the "big picture": the file that represents the
-configuration, and the file that contains the implementation objects
-referenced by the configuration. To avoid this, :app:`Pyramid` allows you to
-insert :term:`configuration decoration` statements very close to code that is
-referred to by the declaration itself. For example:
+because often the code for a single application may live in many files. If the
+configuration is centralized in one place, you'll need to have at least two
+files open at once to see the "big picture": the file that represents the
+configuration, and the file that contains the implementation objects referenced
+by the configuration. To avoid this, :app:`Pyramid` allows you to insert
+:term:`configuration decoration` statements very close to code that is referred
+to by the declaration itself. For example:
.. code-block:: python
:linenos:
@@ -90,20 +89,19 @@ referred to by the declaration itself. For example:
def hello(request):
return Response('Hello')
-The mere existence of configuration decoration doesn't cause any
-configuration registration to be performed. Before it has any effect on the
-configuration of a :app:`Pyramid` application, a configuration decoration
-within application code must be found through a process known as a
-:term:`scan`.
+The mere existence of configuration decoration doesn't cause any configuration
+registration to be performed. Before it has any effect on the configuration of
+a :app:`Pyramid` application, a configuration decoration within application
+code must be found through a process known as a :term:`scan`.
For example, the :class:`pyramid.view.view_config` decorator in the code
-example above adds an attribute to the ``hello`` function, making it
-available for a :term:`scan` to find it later.
+example above adds an attribute to the ``hello`` function, making it available
+for a :term:`scan` to find it later.
-A :term:`scan` of a :term:`module` or a :term:`package` and its subpackages
-for decorations happens when the :meth:`pyramid.config.Configurator.scan`
-method is invoked: scanning implies searching for configuration declarations
-in a package and its subpackages. For example:
+A :term:`scan` of a :term:`module` or a :term:`package` and its subpackages for
+decorations happens when the :meth:`pyramid.config.Configurator.scan` method is
+invoked: scanning implies searching for configuration declarations in a package
+and its subpackages. For example:
.. code-block:: python
:linenos:
@@ -125,16 +123,16 @@ in a package and its subpackages. For example:
server.serve_forever()
The scanning machinery imports each module and subpackage in a package or
-module recursively, looking for special attributes attached to objects
-defined within a module. These special attributes are typically attached to
-code via the use of a :term:`decorator`. For example, the
+module recursively, looking for special attributes attached to objects defined
+within a module. These special attributes are typically attached to code via
+the use of a :term:`decorator`. For example, the
:class:`~pyramid.view.view_config` decorator can be attached to a function or
instance method.
-Once scanning is invoked, and :term:`configuration decoration` is found by
-the scanner, a set of calls are made to a :term:`Configurator` on your
-behalf: these calls replace the need to add imperative configuration
-statements that don't live near the code being configured.
+Once scanning is invoked, and :term:`configuration decoration` is found by the
+scanner, a set of calls are made to a :term:`Configurator` on your behalf.
+These calls replace the need to add imperative configuration statements that
+don't live near the code being configured.
The combination of :term:`configuration decoration` and the invocation of a
:term:`scan` is collectively known as :term:`declarative configuration`.
@@ -150,7 +148,7 @@ In the example above, the scanner translates the arguments to
Summary
-------
-There are two ways to configure a :app:`Pyramid` application: declaratively
-and imperatively. You can choose the mode you're most comfortable with; both
-are completely equivalent. Examples in this documentation will use both
-modes interchangeably.
+There are two ways to configure a :app:`Pyramid` application: declaratively and
+imperatively. You can choose the mode with which you're most comfortable; both
+are completely equivalent. Examples in this documentation will use both modes
+interchangeably.
diff --git a/docs/narr/firstapp.rst b/docs/narr/firstapp.rst
index e73ef66ac..6a952dec9 100644
--- a/docs/narr/firstapp.rst
+++ b/docs/narr/firstapp.rst
@@ -4,7 +4,7 @@
.. _firstapp_chapter:
Creating Your First :app:`Pyramid` Application
-=================================================
+==============================================
In this chapter, we will walk through the creation of a tiny :app:`Pyramid`
application. After we're finished creating the application, we'll explain in
@@ -37,28 +37,27 @@ On Windows:
C:\> %VENV%\Scripts\python.exe helloworld.py
-This command will not return and nothing will be printed to the console.
-When port 8080 is visited by a browser on the URL ``/hello/world``, the
-server will simply serve up the text "Hello world!". If your application is
-running on your local system, using `<http://localhost:8080/hello/world>`_
-in a browser will show this result.
+This command will not return and nothing will be printed to the console. When
+port 8080 is visited by a browser on the URL ``/hello/world``, the server will
+simply serve up the text "Hello world!". If your application is running on
+your local system, using `<http://localhost:8080/hello/world>`_ in a browser
+will show this result.
Each time you visit a URL served by the application in a browser, a logging
line will be emitted to the console displaying the hostname, the date, the
-request method and path, and some additional information. This output is
-done by the wsgiref server we've used to serve this application. It logs an
-"access log" in Apache combined logging format to the console.
+request method and path, and some additional information. This output is done
+by the wsgiref server we've used to serve this application. It logs an "access
+log" in Apache combined logging format to the console.
Press ``Ctrl-C`` (or ``Ctrl-Break`` on Windows) to stop the application.
Now that we have a rudimentary understanding of what the application does,
-let's examine it piece-by-piece.
+let's examine it piece by piece.
Imports
~~~~~~~
-The above ``helloworld.py`` script uses the following set of import
-statements:
+The above ``helloworld.py`` script uses the following set of import statements:
.. literalinclude:: helloworld.py
:linenos:
@@ -71,32 +70,32 @@ The script imports the :class:`~pyramid.config.Configurator` class from the
Like many other Python web frameworks, :app:`Pyramid` uses the :term:`WSGI`
protocol to connect an application and a web server together. The
-:mod:`wsgiref` server is used in this example as a WSGI server for
-convenience, as it is shipped within the Python standard library.
+:mod:`wsgiref` server is used in this example as a WSGI server for convenience,
+as it is shipped within the Python standard library.
-The script also imports the :class:`pyramid.response.Response` class for
-later use. An instance of this class will be used to create a web response.
+The script also imports the :class:`pyramid.response.Response` class for later
+use. An instance of this class will be used to create a web response.
View Callable Declarations
~~~~~~~~~~~~~~~~~~~~~~~~~~
-The above script, beneath its set of imports, defines a function
-named ``hello_world``.
+The above script, beneath its set of imports, defines a function named
+``hello_world``.
.. literalinclude:: helloworld.py
:linenos:
:pyobject: hello_world
-The function accepts a single argument (``request``) and it returns an
-instance of the :class:`pyramid.response.Response` class. The single
-argument to the class' constructor is a string computed from parameters
-matched from the URL. This value becomes the body of the response.
+The function accepts a single argument (``request``) and it returns an instance
+of the :class:`pyramid.response.Response` class. The single argument to the
+class' constructor is a string computed from parameters matched from the URL.
+This value becomes the body of the response.
-This function is known as a :term:`view callable`. A view callable
-accepts a single argument, ``request``. It is expected to return a
-:term:`response` object. A view callable doesn't need to be a function; it
-can be represented via another type of object, like a class or an instance,
-but for our purposes here, a function serves us well.
+This function is known as a :term:`view callable`. A view callable accepts a
+single argument, ``request``. It is expected to return a :term:`response`
+object. A view callable doesn't need to be a function; it can be represented
+via another type of object, like a class or an instance, but for our purposes
+here, a function serves us well.
A view callable is always called with a :term:`request` object. A request
object is a representation of an HTTP request sent to :app:`Pyramid` via the
@@ -105,10 +104,10 @@ active :term:`WSGI` server.
A view callable is required to return a :term:`response` object because a
response object has all the information necessary to formulate an actual HTTP
response; this object is then converted to text by the :term:`WSGI` server
-which called Pyramid and it is sent back to the requesting browser. To
-return a response, each view callable creates an instance of the
-:class:`~pyramid.response.Response` class. In the ``hello_world`` function,
-a string is passed as the body to the response.
+which called Pyramid and it is sent back to the requesting browser. To return
+a response, each view callable creates an instance of the
+:class:`~pyramid.response.Response` class. In the ``hello_world`` function, a
+string is passed as the body to the response.
.. index::
single: imperative configuration
@@ -120,16 +119,16 @@ a string is passed as the body to the response.
Application Configuration
~~~~~~~~~~~~~~~~~~~~~~~~~
-In the above script, the following code represents the *configuration* of
-this simple application. The application is configured using the previously
-defined imports and function definitions, placed within the confines of an
-``if`` statement:
+In the above script, the following code represents the *configuration* of this
+simple application. The application is configured using the previously defined
+imports and function definitions, placed within the confines of an ``if``
+statement:
.. literalinclude:: helloworld.py
:linenos:
:lines: 9-15
-Let's break this down piece-by-piece.
+Let's break this down piece by piece.
Configurator Construction
~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -140,26 +139,26 @@ Configurator Construction
The ``if __name__ == '__main__':`` line in the code sample above represents a
Python idiom: the code inside this if clause is not invoked unless the script
-containing this code is run directly from the operating system command
-line. For example, if the file named ``helloworld.py`` contains the entire
-script body, the code within the ``if`` statement will only be invoked when
-``python helloworld.py`` is executed from the command line.
-
-Using the ``if`` clause is necessary -- or at least best practice -- because
-code in a Python ``.py`` file may be eventually imported via the Python
-``import`` statement by another ``.py`` file. ``.py`` files that are
-imported by other ``.py`` files are referred to as *modules*. By using the
-``if __name__ == '__main__':`` idiom, the script above is indicating that it does
-not want the code within the ``if`` statement to execute if this module is
-imported from another; the code within the ``if`` block should only be run
-during a direct script execution.
+containing this code is run directly from the operating system command line.
+For example, if the file named ``helloworld.py`` contains the entire script
+body, the code within the ``if`` statement will only be invoked when ``python
+helloworld.py`` is executed from the command line.
+
+Using the ``if`` clause is necessary—or at least best practice—because code in
+a Python ``.py`` file may be eventually imported via the Python ``import``
+statement by another ``.py`` file. ``.py`` files that are imported by other
+``.py`` files are referred to as *modules*. By using the ``if __name__ ==
+'__main__':`` idiom, the script above is indicating that it does not want the
+code within the ``if`` statement to execute if this module is imported from
+another; the code within the ``if`` block should only be run during a direct
+script execution.
The ``config = Configurator()`` line above creates an instance of the
:class:`~pyramid.config.Configurator` class. The resulting ``config`` object
represents an API which the script uses to configure this particular
:app:`Pyramid` application. Methods called on the Configurator will cause
-registrations to be made in an :term:`application registry` associated with
-the application.
+registrations to be made in an :term:`application registry` associated with the
+application.
.. _adding_configuration:
@@ -170,13 +169,13 @@ Adding Configuration
:linenos:
:lines: 11-12
-First line above calls the :meth:`pyramid.config.Configurator.add_route`
-method, which registers a :term:`route` to match any URL path that begins
-with ``/hello/`` followed by a string.
+The first line above calls the :meth:`pyramid.config.Configurator.add_route`
+method, which registers a :term:`route` to match any URL path that begins with
+``/hello/`` followed by a string.
-The second line registers the ``hello_world`` function as a
-:term:`view callable` and makes sure that it will be called when the
-``hello`` route is matched.
+The second line registers the ``hello_world`` function as a :term:`view
+callable` and makes sure that it will be called when the ``hello`` route is
+matched.
.. index::
single: make_wsgi_app
@@ -190,25 +189,24 @@ WSGI Application Creation
:lines: 13
After configuring views and ending configuration, the script creates a WSGI
-*application* via the :meth:`pyramid.config.Configurator.make_wsgi_app`
-method. A call to ``make_wsgi_app`` implies that all configuration is
-finished (meaning all method calls to the configurator, which sets up views
-and various other configuration settings, have been performed). The
-``make_wsgi_app`` method returns a :term:`WSGI` application object that can
-be used by any WSGI server to present an application to a requestor.
-:term:`WSGI` is a protocol that allows servers to talk to Python
-applications. We don't discuss :term:`WSGI` in any depth within this book,
-but you can learn more about it by visiting `wsgi.org
-<http://wsgi.org>`_.
-
-The :app:`Pyramid` application object, in particular, is an instance of a
-class representing a :app:`Pyramid` :term:`router`. It has a reference to
-the :term:`application registry` which resulted from method calls to the
-configurator used to configure it. The :term:`router` consults the registry
-to obey the policy choices made by a single application. These policy
-choices were informed by method calls to the :term:`Configurator` made
-earlier; in our case, the only policy choices made were implied by calls
-to its ``add_view`` and ``add_route`` methods.
+*application* via the :meth:`pyramid.config.Configurator.make_wsgi_app` method.
+A call to ``make_wsgi_app`` implies that all configuration is finished
+(meaning all method calls to the configurator, which sets up views and various
+other configuration settings, have been performed). The ``make_wsgi_app``
+method returns a :term:`WSGI` application object that can be used by any WSGI
+server to present an application to a requestor. :term:`WSGI` is a protocol
+that allows servers to talk to Python applications. We don't discuss
+:term:`WSGI` in any depth within this book, but you can learn more about it by
+visiting `wsgi.org <http://wsgi.org>`_.
+
+The :app:`Pyramid` application object, in particular, is an instance of a class
+representing a :app:`Pyramid` :term:`router`. It has a reference to the
+:term:`application registry` which resulted from method calls to the
+configurator used to configure it. The :term:`router` consults the registry to
+obey the policy choices made by a single application. These policy choices
+were informed by method calls to the :term:`Configurator` made earlier; in our
+case, the only policy choices made were implied by calls to its ``add_view``
+and ``add_route`` methods.
WSGI Application Serving
~~~~~~~~~~~~~~~~~~~~~~~~
@@ -217,37 +215,36 @@ WSGI Application Serving
:linenos:
:lines: 14-15
-Finally, we actually serve the application to requestors by starting up a
-WSGI server. We happen to use the :mod:`wsgiref` ``make_server`` server
-maker for this purpose. We pass in as the first argument ``'0.0.0.0'``,
-which means "listen on all TCP interfaces." By default, the HTTP server
-listens only on the ``127.0.0.1`` interface, which is problematic if you're
-running the server on a remote system and you wish to access it with a web
-browser from a local system. We also specify a TCP port number to listen on,
-which is 8080, passing it as the second argument. The final argument is the
-``app`` object (a :term:`router`), which is the application we wish to
-serve. Finally, we call the server's ``serve_forever`` method, which starts
-the main loop in which it will wait for requests from the outside world.
-
-When this line is invoked, it causes the server to start listening on TCP
-port 8080. The server will serve requests forever, or at least until we stop
-it by killing the process which runs it (usually by pressing ``Ctrl-C``
-or ``Ctrl-Break`` in the terminal we used to start it).
+Finally, we actually serve the application to requestors by starting up a WSGI
+server. We happen to use the :mod:`wsgiref` ``make_server`` server maker for
+this purpose. We pass in as the first argument ``'0.0.0.0'``, which means
+"listen on all TCP interfaces". By default, the HTTP server listens only on
+the ``127.0.0.1`` interface, which is problematic if you're running the server
+on a remote system and you wish to access it with a web browser from a local
+system. We also specify a TCP port number to listen on, which is 8080, passing
+it as the second argument. The final argument is the ``app`` object (a
+:term:`router`), which is the application we wish to serve. Finally, we call
+the server's ``serve_forever`` method, which starts the main loop in which it
+will wait for requests from the outside world.
+
+When this line is invoked, it causes the server to start listening on TCP port
+8080. The server will serve requests forever, or at least until we stop it by
+killing the process which runs it (usually by pressing ``Ctrl-C`` or
+``Ctrl-Break`` in the terminal we used to start it).
Conclusion
~~~~~~~~~~
Our hello world application is one of the simplest possible :app:`Pyramid`
applications, configured "imperatively". We can see that it's configured
-imperatively because the full power of Python is available to us as we
-perform configuration tasks.
+imperatively because the full power of Python is available to us as we perform
+configuration tasks.
References
----------
-For more information about the API of a :term:`Configurator` object,
-see :class:`~pyramid.config.Configurator` .
+For more information about the API of a :term:`Configurator` object, see
+:class:`~pyramid.config.Configurator` .
For more information about :term:`view configuration`, see
:ref:`view_config_chapter`.
-
diff --git a/docs/narr/install.rst b/docs/narr/install.rst
index 0f114a9c7..26d458727 100644
--- a/docs/narr/install.rst
+++ b/docs/narr/install.rst
@@ -1,7 +1,7 @@
.. _installing_chapter:
Installing :app:`Pyramid`
-============================
+=========================
.. index::
single: install preparation
@@ -15,8 +15,8 @@ You will need `Python <http://python.org>`_ version 2.6 or better to run
.. sidebar:: Python Versions
As of this writing, :app:`Pyramid` has been tested under Python 2.6, Python
- 2.7, Python 3.2, Python 3.3, Python 3.4 and PyPy 2.2. :app:`Pyramid` does
- not run under any version of Python before 2.6.
+ 2.7, Python 3.2, Python 3.3, Python 3.4, PyPy, and PyPy3. :app:`Pyramid`
+ does not run under any version of Python before 2.6.
:app:`Pyramid` is known to run on all popular UNIX-like systems such as Linux,
Mac OS X, and FreeBSD as well as on Windows platforms. It is also known to run
@@ -32,9 +32,9 @@ dependency will fall back to using pure Python instead.
For Mac OS X Users
~~~~~~~~~~~~~~~~~~
-Python comes pre-installed on Mac OS X, but due to Apple's release cycle,
-it is often out of date. Unless you have a need for a specific earlier
-version, it is recommended to install the latest 2.x or 3.x version of Python.
+Python comes pre-installed on Mac OS X, but due to Apple's release cycle, it is
+often out of date. Unless you have a need for a specific earlier version, it is
+recommended to install the latest 2.x or 3.x version of Python.
You can install the latest verion of Python for Mac OS X from the binaries on
`python.org <https://www.python.org/downloads/mac-osx/>`_.
@@ -52,7 +52,7 @@ Alternatively, you can use the `homebrew <http://brew.sh/>`_ package manager.
If you use an installer for your Python, then you can skip to the section
:ref:`installing_unix`.
-If You Don't Yet Have A Python Interpreter (UNIX)
+If You Don't Yet Have a Python Interpreter (UNIX)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If your system doesn't have a Python interpreter, and you're on UNIX, you can
@@ -90,12 +90,12 @@ Source Compile Method
It's useful to use a Python interpreter that *isn't* the "system" Python
interpreter to develop your software. The authors of :app:`Pyramid` tend not
-to use the system Python for development purposes; always a self-compiled one.
+to use the system Python for development purposes; always a self-compiled one.
Compiling Python is usually easy, and often the "system" Python is compiled
with options that aren't optimal for web development. For an explanation, see
https://github.com/Pylons/pyramid/issues/747.
-To compile software on your UNIX system, typically you need development tools.
+To compile software on your UNIX system, typically you need development tools.
Often these can be installed via the package manager. For example, this works
to do so on an Ubuntu Linux system:
@@ -128,7 +128,7 @@ Once these steps are performed, the Python interpreter will be invokable via
.. index::
pair: install; Python (from package, Windows)
-If You Don't Yet Have A Python Interpreter (Windows)
+If You Don't Yet Have a Python Interpreter (Windows)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If your Windows system doesn't have a Python interpreter, you'll need to
@@ -153,7 +153,7 @@ also need to download and install the Python for Windows extensions.
.. _installing_unix:
Installing :app:`Pyramid` on a UNIX System
----------------------------------------------
+------------------------------------------
It is best practice to install :app:`Pyramid` into a "virtual" Python
environment in order to obtain isolation from any "system" packages you've got
@@ -204,7 +204,7 @@ it using the Python interpreter into which you want to install setuptools.
$ python ez_setup.py
-Once this command is invoked, setuptools should be installed on your system.
+Once this command is invoked, setuptools should be installed on your system.
If the command fails due to permission errors, you may need to be the
administrative user on your system to successfully invoke the script. To
remediate this, you may need to do:
@@ -285,8 +285,8 @@ it's an absolute path.
acceptable (and desirable) to create a virtualenv as a normal user.
-Installing :app:`Pyramid` Into the Virtual Python Environment
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Installing :app:`Pyramid` into the Virtual Python Environment
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
After you've got your virtualenv installed, you may install :app:`Pyramid`
itself using the following commands:
@@ -301,9 +301,9 @@ complete, as it downloads and installs a number of dependencies.
.. note::
If you see any warnings and/or errors related to failing to compile the C
- extensions, in most cases you may safely ignore those errors. If you wish
- to use the C extensions, please verify that you have a functioning compiler
- and the Python header files installed.
+ extensions, in most cases you may safely ignore those errors. If you wish to
+ use the C extensions, please verify that you have a functioning compiler and
+ the Python header files installed.
.. index::
single: installing on Windows
@@ -311,7 +311,7 @@ complete, as it downloads and installs a number of dependencies.
.. _installing_windows:
Installing :app:`Pyramid` on a Windows System
--------------------------------------------------
+---------------------------------------------
You can use Pyramid on Windows under Python 2 or 3.
@@ -382,4 +382,3 @@ WebOb, PasteDeploy, and others are installed.
Additionally, as chronicled in :ref:`project_narr`, scaffolds will be
registered, which make it easy to start a new :app:`Pyramid` project.
-
diff --git a/docs/narr/introduction.rst b/docs/narr/introduction.rst
index 2d3cd23e9..7906dd85d 100644
--- a/docs/narr/introduction.rst
+++ b/docs/narr/introduction.rst
@@ -7,7 +7,7 @@
single: framework
:app:`Pyramid` Introduction
-==============================
+===========================
:app:`Pyramid` is a general, open source, Python web application development
*framework*. Its primary goal is to make it easier for a Python developer to
@@ -15,40 +15,39 @@ create web applications.
.. sidebar:: Frameworks vs. Libraries
- A *framework* differs from a *library* in one very important way:
- library code is always *called* by code that you write, while a
- framework always *calls* code that you write. Using a set of
- libraries to create an application is usually easier than using a
- framework initially, because you can choose to cede control to
- library code you have not authored very selectively. But when you
- use a framework, you are required to cede a greater portion of
- control to code you have not authored: code that resides in the
- framework itself. You needn't use a framework at all to create a
- web application using Python. A rich set of libraries already
- exists for the platform. In practice, however, using a framework
- to create an application is often more practical than rolling your
- own via a set of libraries if the framework provides a set of
- facilities that fits your application requirements.
+ A *framework* differs from a *library* in one very important way: library
+ code is always *called* by code that you write, while a framework always
+ *calls* code that you write. Using a set of libraries to create an
+ application is usually easier than using a framework initially, because you
+ can choose to cede control to library code you have not authored very
+ selectively. But when you use a framework, you are required to cede a
+ greater portion of control to code you have not authored: code that resides
+ in the framework itself. You needn't use a framework at all to create a web
+ application using Python. A rich set of libraries already exists for the
+ platform. In practice, however, using a framework to create an application
+ is often more practical than rolling your own via a set of libraries if the
+ framework provides a set of facilities that fits your application
+ requirements.
Pyramid attempts to follow these design and engineering principles:
Simplicity
:app:`Pyramid` takes a *"pay only for what you eat"* approach. You can get
- results even if you have only a partial understanding of :app:`Pyramid`.
- It doesn’t force you to use any particular technology to produce an
- application, and we try to keep the core set of concepts that you need to
- understand to a minimum.
+ results even if you have only a partial understanding of :app:`Pyramid`. It
+ doesn't force you to use any particular technology to produce an application,
+ and we try to keep the core set of concepts that you need to understand to a
+ minimum.
Minimalism
- :app:`Pyramid` tries to solve only the fundamental problems of creating
- a web application: the mapping of URLs to code, templating, security and
- serving static assets. We consider these to be the core activities that are
- common to nearly all web applications.
+ :app:`Pyramid` tries to solve only the fundamental problems of creating a web
+ application: the mapping of URLs to code, templating, security, and serving
+ static assets. We consider these to be the core activities that are common to
+ nearly all web applications.
Documentation
- Pyramid's minimalism means that it is easier for us to maintain complete
- and up-to-date documentation. It is our goal that no aspect of Pyramid
- is undocumented.
+ Pyramid's minimalism means that it is easier for us to maintain complete and
+ up-to-date documentation. It is our goal that no aspect of Pyramid is
+ undocumented.
Speed
:app:`Pyramid` is designed to provide noticeably fast execution for common
@@ -56,12 +55,12 @@ Speed
Reliability
:app:`Pyramid` is developed conservatively and tested exhaustively. Where
- Pyramid source code is concerned, our motto is: "If it ain’t tested, it’s
+ Pyramid source code is concerned, our motto is: "If it ain't tested, it's
broke".
Openness
- As with Python, the Pyramid software is distributed under a `permissive
- open source license <http://repoze.org/license.html>`_.
+ As with Python, the Pyramid software is distributed under a `permissive open
+ source license <http://repoze.org/license.html>`_.
.. _what_makes_pyramid_unique:
@@ -69,55 +68,53 @@ What makes Pyramid unique
-------------------------
Understandably, people don't usually want to hear about squishy engineering
-principles; they want to hear about concrete stuff that solves their
-problems. With that in mind, what would make someone want to use Pyramid
-instead of one of the many other web frameworks available today? What makes
-Pyramid unique?
-
-This is a hard question to answer, because there are lots of excellent
-choices, and it's actually quite hard to make a wrong choice, particularly in
-the Python web framework market. But one reasonable answer is this: you can
-write very small applications in Pyramid without needing to know a lot.
-"What?", you say. "That can't possibly be a unique feature. Lots of other web
-frameworks let you do that!" Well, you're right. But unlike many other
-systems, you can also write very large applications in Pyramid if you learn a
-little more about it. Pyramid will allow you to become productive quickly,
-and will grow with you. It won't hold you back when your application is small,
-and it won't get in your way when your application becomes large. "Well
-that's fine," you say. "Lots of other frameworks let me write large apps,
-too." Absolutely. But other Python web frameworks don't seamlessly let you
-do both. They seem to fall into two non-overlapping categories: frameworks
-for "small apps" and frameworks for "big apps". The "small app" frameworks
-typically sacrifice "big app" features, and vice versa.
+principles; they want to hear about concrete stuff that solves their problems.
+With that in mind, what would make someone want to use Pyramid instead of one
+of the many other web frameworks available today? What makes Pyramid unique?
+
+This is a hard question to answer because there are lots of excellent choices,
+and it's actually quite hard to make a wrong choice, particularly in the Python
+web framework market. But one reasonable answer is this: you can write very
+small applications in Pyramid without needing to know a lot. "What?" you say.
+"That can't possibly be a unique feature. Lots of other web frameworks let you
+do that!" Well, you're right. But unlike many other systems, you can also
+write very large applications in Pyramid if you learn a little more about it.
+Pyramid will allow you to become productive quickly, and will grow with you. It
+won't hold you back when your application is small, and it won't get in your
+way when your application becomes large. "Well that's fine," you say. "Lots of
+other frameworks let me write large apps, too." Absolutely. But other Python
+web frameworks don't seamlessly let you do both. They seem to fall into two
+non-overlapping categories: frameworks for "small apps" and frameworks for "big
+apps". The "small app" frameworks typically sacrifice "big app" features, and
+vice versa.
We don't think it's a universally reasonable suggestion to write "small apps"
in a "small framework" and "big apps" in a "big framework". You can't really
-know to what size every application will eventually grow. We don't really
-want to have to rewrite a previously small application in another framework
-when it gets "too big". We believe the current binary distinction between
-frameworks for small and large applications is just false. A well-designed
-framework should be able to be good at both. Pyramid strives to be that kind
-of framework.
-
-To this end, Pyramid provides a set of features that, combined, are unique
+know to what size every application will eventually grow. We don't really want
+to have to rewrite a previously small application in another framework when it
+gets "too big". We believe the current binary distinction between frameworks
+for small and large applications is just false. A well-designed framework
+should be able to be good at both. Pyramid strives to be that kind of
+framework.
+
+To this end, Pyramid provides a set of features that combined are unique
amongst Python web frameworks. Lots of other frameworks contain some
combination of these features. Pyramid of course actually stole many of them
-from those other frameworks. But Pyramid is the only one that has all of
-them in one place, documented appropriately, and useful *à la carte* without
+from those other frameworks. But Pyramid is the only one that has all of them
+in one place, documented appropriately, and useful *à la carte* without
necessarily paying for the entire banquet. These are detailed below.
Single-file applications
~~~~~~~~~~~~~~~~~~~~~~~~
-You can write a Pyramid application that lives entirely in one Python file,
-not unlike existing Python microframeworks. This is beneficial for one-off
-prototyping, bug reproduction, and very small applications. These
-applications are easy to understand because all the information about the
-application lives in a single place, and you can deploy them without needing
-to understand much about Python distributions and packaging. Pyramid isn't
-really marketed as a microframework, but it allows you to do almost
-everything that frameworks that are marketed as micro offer in very similar
-ways.
+You can write a Pyramid application that lives entirely in one Python file, not
+unlike existing Python microframeworks. This is beneficial for one-off
+prototyping, bug reproduction, and very small applications. These applications
+are easy to understand because all the information about the application lives
+in a single place, and you can deploy them without needing to understand much
+about Python distributions and packaging. Pyramid isn't really marketed as a
+microframework, but it allows you to do almost everything that frameworks that
+are marketed as "micro" offer in very similar ways.
.. literalinclude:: helloworld.py
@@ -142,26 +139,25 @@ decorators to localize the configuration. For example:
def fred_view(request):
return Response('fred')
-However, unlike some other systems, using decorators for Pyramid
-configuration does not make your application difficult to extend, test, or
-reuse. The :class:`~pyramid.view.view_config` decorator, for example, does
-not actually *change* the input or output of the function it decorates, so
-testing it is a "WYSIWYG" operation. You don't need to understand the
-framework to test your own code. You just behave as if the decorator is not
-there. You can also instruct Pyramid to ignore some decorators, or use
-completely imperative configuration instead of decorators to add views.
-Pyramid decorators are inert instead of eager. You detect and activate them
-with a :term:`scan`.
+However, unlike some other systems, using decorators for Pyramid configuration
+does not make your application difficult to extend, test, or reuse. The
+:class:`~pyramid.view.view_config` decorator, for example, does not actually
+*change* the input or output of the function it decorates, so testing it is a
+"WYSIWYG" operation. You don't need to understand the framework to test your
+own code. You just behave as if the decorator is not there. You can also
+instruct Pyramid to ignore some decorators, or use completely imperative
+configuration instead of decorators to add views. Pyramid decorators are inert
+instead of eager. You detect and activate them with a :term:`scan`.
Example: :ref:`mapping_views_using_a_decorator_section`.
URL generation
~~~~~~~~~~~~~~
-Pyramid is capable of generating URLs for resources, routes, and static
-assets. Its URL generation APIs are easy to use and flexible. If you use
-Pyramid's various APIs for generating URLs, you can change your configuration
-around arbitrarily without fear of breaking a link on one of your web pages.
+Pyramid is capable of generating URLs for resources, routes, and static assets.
+Its URL generation APIs are easy to use and flexible. If you use Pyramid's
+various APIs for generating URLs, you can change your configuration around
+arbitrarily without fear of breaking a link on one of your web pages.
Example: :ref:`generating_route_urls`.
@@ -169,12 +165,12 @@ Static file serving
~~~~~~~~~~~~~~~~~~~
Pyramid is perfectly willing to serve static files itself. It won't make you
-use some external web server to do that. You can even serve more than one
-set of static files in a single Pyramid web application (e.g. ``/static`` and
-``/static2``). You can optionally place your files on an external web
-server and ask Pyramid to help you generate URLs to those files. This let's
-you use Pyramid's internal file serving while doing development, and a faster
-static file server in production, without changing any code.
+use some external web server to do that. You can even serve more than one set
+of static files in a single Pyramid web application (e.g., ``/static`` and
+``/static2``). You can optionally place your files on an external web server
+and ask Pyramid to help you generate URLs to those files. This let's you use
+Pyramid's internal file serving while doing development, and a faster static
+file server in production, without changing any code.
Example: :ref:`static_assets_section`.
@@ -189,10 +185,10 @@ code. Plain old ``print()`` calls used for debugging can display to a console.
Pyramid's debug toolbar comes activated when you use a Pyramid scaffold to
render a project. This toolbar overlays your application in the browser, and
allows you access to framework data, such as the routes configured, the last
-renderings performed, the current set of packages installed, SQLAlchemy
-queries run, logging data, and various other facts. When an exception
-occurs, you can use its interactive debugger to poke around right in your
-browser to try to determine the cause of the exception. It's handy.
+renderings performed, the current set of packages installed, SQLAlchemy queries
+run, logging data, and various other facts. When an exception occurs, you can
+use its interactive debugger to poke around right in your browser to try to
+determine the cause of the exception. It's handy.
Example: :ref:`debug_toolbar`.
@@ -200,29 +196,29 @@ Debugging settings
~~~~~~~~~~~~~~~~~~
Pyramid has debugging settings that allow you to print Pyramid runtime
-information to the console when things aren't behaving as you're expecting.
-For example, you can turn on ``debug_notfound``, which prints an informative
-message to the console every time a URL does not match any view. You can
-turn on ``debug_authorization``, which lets you know why a view execution was
+information to the console when things aren't behaving as you're expecting. For
+example, you can turn on ``debug_notfound``, which prints an informative
+message to the console every time a URL does not match any view. You can turn
+on ``debug_authorization``, which lets you know why a view execution was
allowed or denied by printing a message to the console. These features are
useful for those WTF moments.
There are also a number of commands that you can invoke within a Pyramid
environment that allow you to introspect the configuration of your system.
-``proutes`` shows all configured routes for an application in the order
-they'll be evaluated for matching. ``pviews`` shows all configured views for
-any given URL. These are also WTF-crushers in some circumstances.
+``proutes`` shows all configured routes for an application in the order they'll
+be evaluated for matching. ``pviews`` shows all configured views for any given
+URL. These are also WTF-crushers in some circumstances.
Examples: :ref:`debug_authorization_section` and :ref:`command_line_chapter`.
Add-ons
-~~~~~~~~
+~~~~~~~
Pyramid has an extensive set of add-ons held to the same quality standards as
-the Pyramid core itself. Add-ons are packages which provide functionality
-that the Pyramid core doesn't. Add-on packages already exist which let you
-easily send email, let you use the Jinja2 templating system, let you use
-XML-RPC or JSON-RPC, let you integrate with jQuery Mobile, etc.
+the Pyramid core itself. Add-ons are packages which provide functionality that
+the Pyramid core doesn't. Add-on packages already exist which let you easily
+send email, let you use the Jinja2 templating system, let you use XML-RPC or
+JSON-RPC, let you integrate with jQuery Mobile, etc.
Examples:
http://docs.pylonsproject.org/en/latest/docs/pyramid.html#pyramid-add-on-documentation
@@ -230,16 +226,16 @@ http://docs.pylonsproject.org/en/latest/docs/pyramid.html#pyramid-add-on-documen
Class-based and function-based views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Pyramid has a structured, unified concept of a :term:`view callable`.
-View callables can be functions, methods of classes, or even instances. When
-you add a new view callable, you can choose to make it a function or a method
-of a class. In either case Pyramid treats it largely the same way. You can
-change your mind later and move code between methods of classes and
-functions. A collection of similar view callables can be attached to a
-single class as methods, if that floats your boat, and they can share
-initialization code as necessary. All kinds of views are easy to understand
-and use, and operate similarly. There is no phony distinction between them.
-They can be used for the same purposes.
+Pyramid has a structured, unified concept of a :term:`view callable`. View
+callables can be functions, methods of classes, or even instances. When you
+add a new view callable, you can choose to make it a function or a method of a
+class. In either case Pyramid treats it largely the same way. You can change
+your mind later and move code between methods of classes and functions. A
+collection of similar view callables can be attached to a single class as
+methods, if that floats your boat, and they can share initialization code as
+necessary. All kinds of views are easy to understand and use, and operate
+similarly. There is no phony distinction between them. They can be used for
+the same purposes.
Here's a view callable defined as a function:
@@ -282,22 +278,22 @@ Here's a few views defined as methods of a class instead:
Asset specifications
~~~~~~~~~~~~~~~~~~~~
-Asset specifications are strings that contain both a Python package name and
-a file or directory name, e.g., ``MyPackage:static/index.html``. Use of these
-specifications is omnipresent in Pyramid. An asset specification can refer
-to a template, a translation directory, or any other package-bound static
+Asset specifications are strings that contain both a Python package name and a
+file or directory name, e.g., ``MyPackage:static/index.html``. Use of these
+specifications is omnipresent in Pyramid. An asset specification can refer to
+a template, a translation directory, or any other package-bound static
resource. This makes a system built on Pyramid extensible because you don't
have to rely on globals ("*the* static directory") or lookup schemes ("*the*
ordered set of template directories") to address your files. You can move
files around as necessary, and include other packages that may not share your
system's templates or static files without encountering conflicts.
-Because asset specifications are used heavily in Pyramid, we've also provided
-a way to allow users to override assets. Say you love a system that someone
-else has created with Pyramid but you just need to change "that one template"
-to make it all better. No need to fork the application. Just override the
-asset specification for that template with your own inside a wrapper, and
-you're good to go.
+Because asset specifications are used heavily in Pyramid, we've also provided a
+way to allow users to override assets. Say you love a system that someone else
+has created with Pyramid but you just need to change "that one template" to
+make it all better. No need to fork the application. Just override the asset
+specification for that template with your own inside a wrapper, and you're good
+to go.
Examples: :ref:`asset_specifications` and :ref:`overriding_assets_section`.
@@ -309,12 +305,11 @@ Templating systems such as Mako, Genshi, Chameleon, and Jinja2 can be treated
as renderers. Renderer bindings for all of these templating systems already
exist for use in Pyramid. But if you'd rather use another, it's not a big
deal. Just copy the code from an existing renderer package, and plug in your
-favorite templating system. You'll then be able to use that templating
-system from within Pyramid just as you'd use one of the "built-in" templating
-systems.
+favorite templating system. You'll then be able to use that templating system
+from within Pyramid just as you'd use one of the "built-in" templating systems.
-Pyramid does not make you use a single templating system exclusively. You
-can use multiple templating systems, even in the same project.
+Pyramid does not make you use a single templating system exclusively. You can
+use multiple templating systems, even in the same project.
Example: :ref:`templates_used_directly`.
@@ -322,12 +317,12 @@ Rendered views can return dictionaries
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you use a :term:`renderer`, you don't have to return a special kind of
-"webby" ``Response`` object from a view. Instead, you can return a
-dictionary, and Pyramid will take care of converting that dictionary
-to a Response using a template on your behalf. This makes the view easier to
-test, because you don't have to parse HTML in your tests; instead just make an
-assertion that the view returns "the right stuff" in the dictionary. You can
-write "real" unit tests instead of functionally testing all of your views.
+"webby" ``Response`` object from a view. Instead you can return a dictionary,
+and Pyramid will take care of converting that dictionary to a Response using a
+template on your behalf. This makes the view easier to test, because you don't
+have to parse HTML in your tests. Instead just make an assertion that the view
+returns "the right stuff" in the dictionary. You can write "real" unit tests
+instead of functionally testing all of your views.
.. index::
pair: renderer; explicitly calling
@@ -363,7 +358,7 @@ be rendered to a response on your behalf. The string passed as ``renderer=``
above is an :term:`asset specification`. It is in the form
``packagename:directoryname/filename.ext``. In this case, it refers to the
``mytemplate.pt`` file in the ``templates`` directory within the ``myapp``
-Python package. Asset specifications are omnipresent in Pyramid: see
+Python package. Asset specifications are omnipresent in Pyramid. See
:ref:`intro_asset_specs` for more information.
Example: :ref:`renderers_chapter`.
@@ -372,9 +367,9 @@ Event system
~~~~~~~~~~~~
Pyramid emits *events* during its request processing lifecycle. You can
-subscribe any number of listeners to these events. For example, to be
-notified of a new request, you can subscribe to the ``NewRequest`` event. To
-be notified that a template is about to be rendered, you can subscribe to the
+subscribe any number of listeners to these events. For example, to be notified
+of a new request, you can subscribe to the ``NewRequest`` event. To be
+notified that a template is about to be rendered, you can subscribe to the
``BeforeRender`` event, and so forth. Using an event publishing system as a
framework notification feature instead of hardcoded hook points tends to make
systems based on that framework less brittle.
@@ -382,9 +377,9 @@ systems based on that framework less brittle.
You can also use Pyramid's event system to send your *own* events. For
example, if you'd like to create a system that is itself a framework, and may
want to notify subscribers that a document has just been indexed, you can
-create your own event type (``DocumentIndexed`` perhaps) and send the event
-via Pyramid. Users of this framework can then subscribe to your event like
-they'd subscribe to the events that are normally sent by Pyramid itself.
+create your own event type (``DocumentIndexed`` perhaps) and send the event via
+Pyramid. Users of this framework can then subscribe to your event like they'd
+subscribe to the events that are normally sent by Pyramid itself.
Example: :ref:`events_chapter` and :ref:`event_types`.
@@ -394,7 +389,7 @@ Built-in internationalization
Pyramid ships with internationalization-related features in its core:
localization, pluralization, and creating message catalogs from source files
and templates. Pyramid allows for a plurality of message catalogs via the use
-of translation domains: you can create a system that has its own translations
+of translation domains. You can create a system that has its own translations
without conflict with other translations in other domains.
Example: :ref:`i18n_chapter`.
@@ -402,9 +397,9 @@ Example: :ref:`i18n_chapter`.
HTTP caching
~~~~~~~~~~~~
-Pyramid provides an easy way to associate views with HTTP caching policies.
-You can just tell Pyramid to configure your view with an ``http_cache``
-statement, and it will take care of the rest::
+Pyramid provides an easy way to associate views with HTTP caching policies. You
+can just tell Pyramid to configure your view with an ``http_cache`` statement,
+and it will take care of the rest::
@view_config(http_cache=3600) # 60 minutes
def myview(request): ....
@@ -412,8 +407,8 @@ statement, and it will take care of the rest::
Pyramid will add appropriate ``Cache-Control`` and ``Expires`` headers to
responses generated when this view is invoked.
-See the :meth:`~pyramid.config.Configurator.add_view` method's
-``http_cache`` documentation for more information.
+See the :meth:`~pyramid.config.Configurator.add_view` method's ``http_cache``
+documentation for more information.
Sessions
~~~~~~~~
@@ -422,9 +417,9 @@ Pyramid has built-in HTTP sessioning. This allows you to associate data with
otherwise anonymous users between requests. Lots of systems do this. But
Pyramid also allows you to plug in your own sessioning system by creating some
code that adheres to a documented interface. Currently there is a binding
-package for the third-party Redis sessioning system that does exactly this.
-But if you have a specialized need (perhaps you want to store your session data
-in MongoDB), you can. You can even switch between implementations without
+package for the third-party Redis sessioning system that does exactly this. But
+if you have a specialized need (perhaps you want to store your session data in
+MongoDB), you can. You can even switch between implementations without
changing your application code.
Example: :ref:`sessions_chapter`.
@@ -432,17 +427,16 @@ Example: :ref:`sessions_chapter`.
Speed
~~~~~
-The Pyramid core is, as far as we can tell, at least marginally faster than
-any other existing Python web framework. It has been engineered from the
-ground up for speed. It only does as much work as absolutely necessary when
-you ask it to get a job done. Extraneous function calls and suboptimal
-algorithms in its core codepaths are avoided. It is feasible to get, for
-example, between 3500 and 4000 requests per second from a simple Pyramid view
-on commodity dual-core laptop hardware and an appropriate WSGI server
-(mod_wsgi or gunicorn). In any case, performance statistics are largely
-useless without requirements and goals, but if you need speed, Pyramid will
-almost certainly never be your application's bottleneck; at least no more
-than Python will be a bottleneck.
+The Pyramid core is, as far as we can tell, at least marginally faster than any
+other existing Python web framework. It has been engineered from the ground up
+for speed. It only does as much work as absolutely necessary when you ask it
+to get a job done. Extraneous function calls and suboptimal algorithms in its
+core codepaths are avoided. It is feasible to get, for example, between 3500
+and 4000 requests per second from a simple Pyramid view on commodity dual-core
+laptop hardware and an appropriate WSGI server (mod_wsgi or gunicorn). In any
+case, performance statistics are largely useless without requirements and
+goals, but if you need speed, Pyramid will almost certainly never be your
+application's bottleneck; at least no more than Python will be a bottleneck.
Example: http://blog.curiasolutions.com/pages/the-great-web-framework-shootout.html
@@ -456,9 +450,9 @@ views, but they're only invoked when an exception "bubbles up" to Pyramid
itself. For example, you might register an exception view for the
:exc:`Exception` exception, which will catch *all* exceptions, and present a
pretty "well, this is embarrassing" page. Or you might choose to register an
-exception view for only specific kinds of application-specific exceptions,
-such as an exception that happens when a file is not found, or an exception
-that happens when an action cannot be performed because the user doesn't have
+exception view for only specific kinds of application-specific exceptions, such
+as an exception that happens when a file is not found, or an exception that
+happens when an action cannot be performed because the user doesn't have
permission to do something. In the former case, you can show a pretty "Not
Found" page; in the latter case you might show a login form.
@@ -468,61 +462,59 @@ No singletons
~~~~~~~~~~~~~
Pyramid is written in such a way that it requires your application to have
-exactly zero "singleton" data structures. Or put another way, Pyramid
-doesn't require you to construct any "mutable globals". Or put even a
-different way, an import of a Pyramid application needn't have any
-"import-time side effects". This is esoteric-sounding, but if you've ever
-tried to cope with parameterizing a Django ``settings.py`` file for multiple
-installations of the same application, or if you've ever needed to
-monkey-patch some framework fixture so that it behaves properly for your use
-case, or if you've ever wanted to deploy your system using an asynchronous
-server, you'll end up appreciating this feature. It just won't be a problem.
-You can even run multiple copies of a similar but not identically configured
-Pyramid application within the same Python process. This is good for shared
-hosting environments, where RAM is at a premium.
+exactly zero "singleton" data structures. Or put another way, Pyramid doesn't
+require you to construct any "mutable globals". Or put even another different
+way, an import of a Pyramid application needn't have any "import-time side
+effects". This is esoteric-sounding, but if you've ever tried to cope with
+parameterizing a Django ``settings.py`` file for multiple installations of the
+same application, or if you've ever needed to monkey-patch some framework
+fixture so that it behaves properly for your use case, or if you've ever wanted
+to deploy your system using an asynchronous server, you'll end up appreciating
+this feature. It just won't be a problem. You can even run multiple copies of
+a similar but not identically configured Pyramid application within the same
+Python process. This is good for shared hosting environments, where RAM is at
+a premium.
View predicates and many views per route
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unlike many other systems, Pyramid allows you to associate more than one view
-per route. For example, you can create a route with the pattern ``/items``
-and when the route is matched, you can shuffle off the request to one view if
-the request method is GET, another view if the request method is POST, etc.
-A system known as "view predicates" allows for this. Request method matching
-is the most basic thing you can do with a view predicate. You can also
-associate views with other request parameters such as the elements in the
-query string, the Accept header, whether the request is an XHR request or
-not, and lots of other things. This feature allows you to keep your
-individual views clean. They won't need much conditional logic, so they'll
-be easier to test.
+per route. For example, you can create a route with the pattern ``/items`` and
+when the route is matched, you can shuffle off the request to one view if the
+request method is GET, another view if the request method is POST, etc. A
+system known as "view predicates" allows for this. Request method matching is
+the most basic thing you can do with a view predicate. You can also associate
+views with other request parameters, such as the elements in the query string,
+the Accept header, whether the request is an XHR request or not, and lots of
+other things. This feature allows you to keep your individual views clean.
+They won't need much conditional logic, so they'll be easier to test.
Example: :ref:`view_configuration_parameters`.
Transaction management
~~~~~~~~~~~~~~~~~~~~~~
-Pyramid's :term:`scaffold` system renders projects that include a
-*transaction management* system, stolen from Zope. When you use this
-transaction management system, you cease being responsible for committing
-your data anymore. Instead Pyramid takes care of committing: it commits at
-the end of a request or aborts if there's an exception. Why is that a good
-thing? Having a centralized place for transaction management is a great
-thing. If instead of managing your transactions in a centralized place you
-sprinkle ``session.commit`` calls in your application logic itself, you can
-wind up in a bad place. Wherever you manually commit data to your database,
-it's likely that some of your other code is going to run *after* your commit.
-If that code goes on to do other important things after that commit, and an
-error happens in the later code, you can easily wind up with inconsistent
-data if you're not extremely careful. Some data will have been written to
-the database that probably should not have. Having a centralized commit
-point saves you from needing to think about this; it's great for lazy people
-who also care about data integrity. Either the request completes
-successfully, and all changes are committed, or it does not, and all changes
-are aborted.
-
-Pyramid's transaction management system allows you to synchronize
-commits between multiple databases. It also allows you to do things like
-conditionally send email if a transaction commits, but otherwise keep quiet.
+Pyramid's :term:`scaffold` system renders projects that include a *transaction
+management* system, stolen from Zope. When you use this transaction management
+system, you cease being responsible for committing your data anymore. Instead
+Pyramid takes care of committing: it commits at the end of a request or aborts
+if there's an exception. Why is that a good thing? Having a centralized place
+for transaction management is a great thing. If, instead of managing your
+transactions in a centralized place, you sprinkle ``session.commit`` calls in
+your application logic itself, you can wind up in a bad place. Wherever you
+manually commit data to your database, it's likely that some of your other code
+is going to run *after* your commit. If that code goes on to do other important
+things after that commit, and an error happens in the later code, you can
+easily wind up with inconsistent data if you're not extremely careful. Some
+data will have been written to the database that probably should not have.
+Having a centralized commit point saves you from needing to think about this;
+it's great for lazy people who also care about data integrity. Either the
+request completes successfully, and all changes are committed, or it does not,
+and all changes are aborted.
+
+Pyramid's transaction management system allows you to synchronize commits
+between multiple databases. It also allows you to do things like conditionally
+send email if a transaction commits, but otherwise keep quiet.
Example: :ref:`bfg_sql_wiki_tutorial` (note the lack of commit statements
anywhere in application code).
@@ -530,18 +522,18 @@ anywhere in application code).
Configuration conflict detection
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-When a system is small, it's reasonably easy to keep it all in your head.
-But when systems grow large, you may have hundreds or thousands of
-configuration statements which add a view, add a route, and so forth.
+When a system is small, it's reasonably easy to keep it all in your head. But
+when systems grow large, you may have hundreds or thousands of configuration
+statements which add a view, add a route, and so forth.
-Pyramid's configuration system keeps track of your configuration statements.
-If you accidentally add two that are identical, or Pyramid can't make
-sense out of what it would mean to have both statements active at the same
-time, it will complain loudly at startup time. It's not dumb though. It will
-automatically resolve conflicting configuration statements on its own if you
-use the configuration :meth:`~pyramid.config.Configurator.include` system.
-"More local" statements are preferred over "less local" ones. This allows
-you to intelligently factor large systems into smaller ones.
+Pyramid's configuration system keeps track of your configuration statements. If
+you accidentally add two that are identical, or Pyramid can't make sense out of
+what it would mean to have both statements active at the same time, it will
+complain loudly at startup time. It's not dumb though. It will automatically
+resolve conflicting configuration statements on its own if you use the
+configuration :meth:`~pyramid.config.Configurator.include` system. "More local"
+statements are preferred over "less local" ones. This allows you to
+intelligently factor large systems into smaller ones.
Example: :ref:`conflict_detection`.
@@ -551,17 +543,17 @@ Configuration extensibility
Unlike other systems, Pyramid provides a structured "include" mechanism (see
:meth:`~pyramid.config.Configurator.include`) that allows you to combine
applications from multiple Python packages. All the configuration statements
-that can be performed in your "main" Pyramid application can also be
-performed by included packages, including the addition of views, routes,
-subscribers, and even authentication and authorization policies. You can even
-extend or override an existing application by including another application's
-configuration in your own, overriding or adding new views and routes to
-it. This has the potential to allow you to create a big application out of
-many other smaller ones. For example, if you want to reuse an existing
-application that already has a bunch of routes, you can just use the
-``include`` statement with a ``route_prefix``. The new application will live
-within your application at an URL prefix. It's not a big deal, and requires
-little up-front engineering effort.
+that can be performed in your "main" Pyramid application can also be performed
+by included packages, including the addition of views, routes, subscribers, and
+even authentication and authorization policies. You can even extend or override
+an existing application by including another application's configuration in
+your own, overriding or adding new views and routes to it. This has the
+potential to allow you to create a big application out of many other smaller
+ones. For example, if you want to reuse an existing application that already
+has a bunch of routes, you can just use the ``include`` statement with a
+``route_prefix``. The new application will live within your application at an
+URL prefix. It's not a big deal, and requires little up-front engineering
+effort.
For example:
@@ -584,16 +576,15 @@ For example:
Flexible authentication and authorization
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Pyramid includes a flexible, pluggable authentication and authorization
-system. No matter where your user data is stored, or what scheme you'd like
-to use to permit your users to access your data, you can use a predefined
-Pyramid plugpoint to plug in your custom authentication and authorization
-code. If you want to change these schemes later, you can just change it in
-one place rather than everywhere in your code. It also ships with prebuilt
-well-tested authentication and authorization schemes out of the box. But
-what if you don't want to use Pyramid's built-in system? You don't have to.
-You can just write your own bespoke security code as you would in any other
-system.
+Pyramid includes a flexible, pluggable authentication and authorization system.
+No matter where your user data is stored, or what scheme you'd like to use to
+permit your users to access your data, you can use a predefined Pyramid
+plugpoint to plug in your custom authentication and authorization code. If you
+want to change these schemes later, you can just change it in one place rather
+than everywhere in your code. It also ships with prebuilt well-tested
+authentication and authorization schemes out of the box. But what if you don't
+want to use Pyramid's built-in system? You don't have to. You can just write
+your own bespoke security code as you would in any other system.
Example: :ref:`enabling_authorization_policy`.
@@ -601,19 +592,19 @@ Traversal
~~~~~~~~~
:term:`Traversal` is a concept stolen from :term:`Zope`. It allows you to
-create a tree of resources, each of which can be addressed by one or more
-URLs. Each of those resources can have one or more *views* associated with
-it. If your data isn't naturally treelike, or you're unwilling to create a
-treelike representation of your data, you aren't going to find traversal
-very useful. However, traversal is absolutely fantastic for sites that need
-to be arbitrarily extensible: it's a lot easier to add a node to a tree than
-it is to shoehorn a route into an ordered list of other routes, or to create
-another entire instance of an application to service a department and glue
-code to allow disparate apps to share data. It's a great fit for sites that
-naturally lend themselves to changing departmental hierarchies, such as
-content management systems and document management systems. Traversal also
-lends itself well to systems that require very granular security ("Bob can
-edit *this* document" as opposed to "Bob can edit documents").
+create a tree of resources, each of which can be addressed by one or more URLs.
+Each of those resources can have one or more *views* associated with it. If
+your data isn't naturally treelike, or you're unwilling to create a treelike
+representation of your data, you aren't going to find traversal very useful.
+However, traversal is absolutely fantastic for sites that need to be
+arbitrarily extensible. It's a lot easier to add a node to a tree than it is to
+shoehorn a route into an ordered list of other routes, or to create another
+entire instance of an application to service a department and glue code to
+allow disparate apps to share data. It's a great fit for sites that naturally
+lend themselves to changing departmental hierarchies, such as content
+management systems and document management systems. Traversal also lends
+itself well to systems that require very granular security ("Bob can edit
+*this* document" as opposed to "Bob can edit documents").
Examples: :ref:`hello_traversal_chapter` and
:ref:`much_ado_about_traversal_chapter`.
@@ -662,12 +653,11 @@ The former is "prettier", right?
Out of the box, if you define the former view callable (the one that simply
returns a string) in Pyramid, when it is executed, Pyramid will raise an
-exception. This is because "explicit is better than implicit", in most
-cases, and by default, Pyramid wants you to return a :term:`Response` object
-from a view callable. This is because there's usually a heck of a lot more
-to a response object than just its body. But if you're the kind of person
-who values such aesthetics, we have an easy way to allow for this sort of
-thing:
+exception. This is because "explicit is better than implicit", in most cases,
+and by default Pyramid wants you to return a :term:`Response` object from a
+view callable. This is because there's usually a heck of a lot more to a
+response object than just its body. But if you're the kind of person who
+values such aesthetics, we have an easy way to allow for this sort of thing:
.. code-block:: python
:linenos:
@@ -733,9 +723,9 @@ Once this is done, both of these view callables will work:
def anotherview(request):
return (403, 'text/plain', "Forbidden")
-Pyramid defaults to explicit behavior, because it's the most generally
-useful, but provides hooks that allow you to adapt the framework to localized
-aesthetic desires.
+Pyramid defaults to explicit behavior, because it's the most generally useful,
+but provides hooks that allow you to adapt the framework to localized aesthetic
+desires.
.. seealso::
@@ -744,9 +734,9 @@ aesthetic desires.
"Global" response object
~~~~~~~~~~~~~~~~~~~~~~~~
-"Constructing these response objects in my view callables is such a chore!
-And I'm way too lazy to register a response adapter, as per the prior
-section," you say. Fine. Be that way:
+"Constructing these response objects in my view callables is such a chore! And
+I'm way too lazy to register a response adapter, as per the prior section," you
+say. Fine. Be that way:
.. code-block:: python
:linenos:
@@ -765,13 +755,13 @@ Automating repetitive configuration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Does Pyramid's configurator allow you to do something, but you're a little
-adventurous and just want it a little less verbose? Or you'd like to offer
-up some handy configuration feature to other Pyramid users without requiring
-that we change Pyramid? You can extend Pyramid's :term:`Configurator` with
-your own directives. For example, let's say you find yourself calling
+adventurous and just want it a little less verbose? Or you'd like to offer up
+some handy configuration feature to other Pyramid users without requiring that
+we change Pyramid? You can extend Pyramid's :term:`Configurator` with your own
+directives. For example, let's say you find yourself calling
:meth:`pyramid.config.Configurator.add_view` repetitively. Usually you can
-take the boring away by using existing shortcuts, but let's say that this is
-a case where there is no such shortcut:
+take the boring away by using existing shortcuts, but let's say that this is a
+case where there is no such shortcut:
.. code-block:: python
:linenos:
@@ -817,7 +807,7 @@ the Configurator object:
Your previously repetitive configuration lines have now morphed into one line.
-You can share your configuration code with others this way too by packaging
+You can share your configuration code with others this way, too, by packaging
it up and calling :meth:`~pyramid.config.Configurator.add_directive` from
within a function called when another user uses the
:meth:`~pyramid.config.Configurator.include` method against your code.
@@ -836,8 +826,7 @@ at the top of the screen based on an enumeration of views they registered.
This is possible using Pyramid's :term:`introspector`.
-Here's an example of using Pyramid's introspector from within a view
-callable:
+Here's an example of using Pyramid's introspector from within a view callable:
.. code-block:: python
:linenos:
@@ -861,8 +850,8 @@ Python 3 compatibility
Pyramid and most of its add-ons are Python 3 compatible. If you develop a
Pyramid application today, you won't need to worry that five years from now
-you'll be backwatered because there are language features you'd like to use
-but your framework doesn't support newer Python versions.
+you'll be backwatered because there are language features you'd like to use but
+your framework doesn't support newer Python versions.
Testing
~~~~~~~
@@ -886,8 +875,8 @@ It's our goal that no Pyramid question go unanswered. Whether you ask a
question on IRC, on the Pylons-discuss mailing list, or on StackOverflow,
you're likely to get a reasonably prompt response. We don't tolerate "support
trolls" or other people who seem to get their rocks off by berating fellow
-users in our various official support channels. We try to keep it well-lit
-and new-user-friendly.
+users in our various official support channels. We try to keep it well-lit and
+new-user-friendly.
Example: Visit irc\://freenode.net#pyramid (the ``#pyramid`` channel on
irc.freenode.net in an IRC client) or the pylons-discuss maillist at
@@ -896,13 +885,12 @@ http://groups.google.com/group/pylons-discuss/.
Documentation
~~~~~~~~~~~~~
-It's a constant struggle, but we try to maintain a balance between
-completeness and new-user-friendliness in the official narrative Pyramid
-documentation (concrete suggestions for improvement are always appreciated,
-by the way). We also maintain a "cookbook" of recipes, which are usually
-demonstrations of common integration scenarios too specific to add to the
-official narrative docs. In any case, the Pyramid documentation is
-comprehensive.
+It's a constant struggle, but we try to maintain a balance between completeness
+and new-user-friendliness in the official narrative Pyramid documentation
+(concrete suggestions for improvement are always appreciated, by the way). We
+also maintain a "cookbook" of recipes, which are usually demonstrations of
+common integration scenarios too specific to add to the official narrative
+docs. In any case, the Pyramid documentation is comprehensive.
Example: The Pyramid Cookbook at
http://docs.pylonsproject.org/projects/pyramid-cookbook/en/latest/.
@@ -929,35 +917,34 @@ includes details about how :app:`Pyramid` relates to the Pylons Project.
------------------------------------------
The first release of Pyramid's predecessor (named :mod:`repoze.bfg`) was made
-in July of 2008. At the end of 2010, we changed the name of
-:mod:`repoze.bfg` to :app:`Pyramid`. It was merged into the Pylons project
-as :app:`Pyramid` in November of that year.
+in July of 2008. At the end of 2010, we changed the name of :mod:`repoze.bfg`
+to :app:`Pyramid`. It was merged into the Pylons project as :app:`Pyramid` in
+November of that year.
-:app:`Pyramid` was inspired by :term:`Zope`, :term:`Pylons` (version
-1.0), and :term:`Django`. As a result, :app:`Pyramid` borrows several
-concepts and features from each, combining them into a unique web
-framework.
+:app:`Pyramid` was inspired by :term:`Zope`, :term:`Pylons` (version 1.0), and
+:term:`Django`. As a result, :app:`Pyramid` borrows several concepts and
+features from each, combining them into a unique web framework.
-Many features of :app:`Pyramid` trace their origins back to :term:`Zope`.
-Like Zope applications, :app:`Pyramid` applications can be easily extended.
-If you obey certain constraints, the application you produce can be reused,
-modified, re-integrated, or extended by third-party developers without
-forking the original application. The concepts of :term:`traversal` and
-declarative security in :app:`Pyramid` were pioneered first in Zope.
+Many features of :app:`Pyramid` trace their origins back to :term:`Zope`. Like
+Zope applications, :app:`Pyramid` applications can be easily extended. If you
+obey certain constraints, the application you produce can be reused, modified,
+re-integrated, or extended by third-party developers without forking the
+original application. The concepts of :term:`traversal` and declarative
+security in :app:`Pyramid` were pioneered first in Zope.
The :app:`Pyramid` concept of :term:`URL dispatch` is inspired by the
:term:`Routes` system used by :term:`Pylons` version 1.0. Like Pylons version
1.0, :app:`Pyramid` is mostly policy-free. It makes no assertions about which
database you should use. Pyramid no longer has built-in templating facilities
as of version 1.5a2, but instead officially supports bindings for templating
-languages, including Chameleon, Jinja2, and Mako. In essence, it only
-supplies a mechanism to map URLs to :term:`view` code, along with a set of
-conventions for calling those views. You are free to use third-party
-components that fit your needs in your applications.
+languages, including Chameleon, Jinja2, and Mako. In essence, it only supplies
+a mechanism to map URLs to :term:`view` code, along with a set of conventions
+for calling those views. You are free to use third-party components that fit
+your needs in your applications.
-The concept of :term:`view` is used by :app:`Pyramid` mostly as it would be
-by Django. :app:`Pyramid` has a documentation culture more like Django's
-than like Zope's.
+The concept of :term:`view` is used by :app:`Pyramid` mostly as it would be by
+Django. :app:`Pyramid` has a documentation culture more like Django's than
+like Zope's.
Like :term:`Pylons` version 1.0, but unlike :term:`Zope`, a :app:`Pyramid`
application developer may use completely imperative code to perform common
@@ -965,34 +952,34 @@ framework configuration tasks such as adding a view or a route. In Zope,
:term:`ZCML` is typically required for similar purposes. In :term:`Grok`, a
Zope-based web framework, :term:`decorator` objects and class-level
declarations are used for this purpose. Out of the box, Pyramid supports
-imperative and decorator-based configuration; :term:`ZCML` may be used via an
+imperative and decorator-based configuration. :term:`ZCML` may be used via an
add-on package named ``pyramid_zcml``.
-Also unlike :term:`Zope` and other "full-stack" frameworks such
-as :term:`Django`, :app:`Pyramid` makes no assumptions about which
-persistence mechanisms you should use to build an application. Zope
-applications are typically reliant on :term:`ZODB`; :app:`Pyramid`
-allows you to build :term:`ZODB` applications, but it has no reliance
-on the ZODB software. Likewise, :term:`Django` tends to assume that
-you want to store your application's data in a relational database.
-:app:`Pyramid` makes no such assumption, allowing you to use a
-relational database, and neither encouraging nor discouraging the decision.
-
-Other Python web frameworks advertise themselves as members of a class
-of web frameworks named `model-view-controller
-<http://en.wikipedia.org/wiki/Model–view–controller>`_ frameworks.
-Insofar as this term has been claimed to represent a class of web
-frameworks, :app:`Pyramid` also generally fits into this class.
-
-.. sidebar:: You Say :app:`Pyramid` is MVC, But Where's The Controller?
-
- The :app:`Pyramid` authors believe that the MVC pattern just doesn't
- really fit the web very well. In a :app:`Pyramid` application, there is a
- resource tree which represents the site structure, and views which tend
- to present the data stored in the resource tree and a user-defined "domain
- model". However, no facility provided *by the framework* actually
- necessarily maps to the concept of a "controller" or "model". So if you
- had to give it some acronym, I guess you'd say :app:`Pyramid` is actually
- an "RV" framework rather than an "MVC" framework. "MVC", however, is
- close enough as a general classification moniker for purposes of
- comparison with other web frameworks.
+Also unlike :term:`Zope` and other "full-stack" frameworks such as
+:term:`Django`, :app:`Pyramid` makes no assumptions about which persistence
+mechanisms you should use to build an application. Zope applications are
+typically reliant on :term:`ZODB`. :app:`Pyramid` allows you to build
+:term:`ZODB` applications, but it has no reliance on the ZODB software.
+Likewise, :term:`Django` tends to assume that you want to store your
+application's data in a relational database. :app:`Pyramid` makes no such
+assumption, allowing you to use a relational database, and neither encouraging
+nor discouraging the decision.
+
+Other Python web frameworks advertise themselves as members of a class of web
+frameworks named `model-view-controller
+<http://en.wikipedia.org/wiki/Model–view–controller>`_ frameworks. Insofar as
+this term has been claimed to represent a class of web frameworks,
+:app:`Pyramid` also generally fits into this class.
+
+.. sidebar:: You Say :app:`Pyramid` is MVC, but Where's the Controller?
+
+ The :app:`Pyramid` authors believe that the MVC pattern just doesn't really
+ fit the web very well. In a :app:`Pyramid` application, there is a resource
+ tree which represents the site structure, and views which tend to present
+ the data stored in the resource tree and a user-defined "domain model".
+ However, no facility provided *by the framework* actually necessarily maps
+ to the concept of a "controller" or "model". So if you had to give it some
+ acronym, I guess you'd say :app:`Pyramid` is actually an "RV" framework
+ rather than an "MVC" framework. "MVC", however, is close enough as a
+ general classification moniker for purposes of comparison with other web
+ frameworks.
diff --git a/docs/narr/project-debug.png b/docs/narr/project-debug.png
index 4f8e441ef..0a703dead 100644
--- a/docs/narr/project-debug.png
+++ b/docs/narr/project-debug.png
Binary files differ
diff --git a/docs/narr/project-show-toolbar.png b/docs/narr/project-show-toolbar.png
new file mode 100644
index 000000000..89b838f64
--- /dev/null
+++ b/docs/narr/project-show-toolbar.png
Binary files differ
diff --git a/docs/narr/project.png b/docs/narr/project.png
index 5d46df0dd..e1afd97d4 100644
--- a/docs/narr/project.png
+++ b/docs/narr/project.png
Binary files differ
diff --git a/docs/narr/project.rst b/docs/narr/project.rst
index 0ada1a379..25f3931e9 100644
--- a/docs/narr/project.rst
+++ b/docs/narr/project.rst
@@ -1,27 +1,26 @@
.. _project_narr:
Creating a :app:`Pyramid` Project
-====================================
+=================================
-As we saw in :ref:`firstapp_chapter`, it's possible to create a
-:app:`Pyramid` application completely manually. However, it's usually more
-convenient to use a :term:`scaffold` to generate a basic :app:`Pyramid`
-:term:`project`.
+As we saw in :ref:`firstapp_chapter`, it's possible to create a :app:`Pyramid`
+application completely manually. However, it's usually more convenient to use
+a :term:`scaffold` to generate a basic :app:`Pyramid` :term:`project`.
A project is a directory that contains at least one Python :term:`package`.
You'll use a scaffold to create a project, and you'll create your application
-logic within a package that lives inside the project. Even if your
-application is extremely simple, it is useful to place code that drives the
-application within a package, because: 1) a package is more easily extended
-with new code and 2) an application that lives inside a package can also be
-distributed more easily than one which does not live within a package.
+logic within a package that lives inside the project. Even if your application
+is extremely simple, it is useful to place code that drives the application
+within a package, because (1) a package is more easily extended with new code,
+and (2) an application that lives inside a package can also be distributed more
+easily than one which does not live within a package.
-:app:`Pyramid` comes with a variety of scaffolds that you can use to generate
-a project. Each scaffold makes different configuration assumptions about
-what type of application you're trying to construct.
+:app:`Pyramid` comes with a variety of scaffolds that you can use to generate a
+project. Each scaffold makes different configuration assumptions about what
+type of application you're trying to construct.
-These scaffolds are rendered using the ``pcreate`` command that is installed
-as part of Pyramid.
+These scaffolds are rendered using the ``pcreate`` command that is installed as
+part of Pyramid.
.. index::
single: scaffolds
@@ -32,28 +31,27 @@ as part of Pyramid.
.. _additional_paster_scaffolds:
Scaffolds Included with :app:`Pyramid`
-------------------------------------------------
+--------------------------------------
-The convenience scaffolds included with :app:`Pyramid` differ from
-each other on a number of axes:
+The convenience scaffolds included with :app:`Pyramid` differ from each other
+on a number of axes:
-- the persistence mechanism they offer (no persistence mechanism,
- :term:`ZODB`, or :term:`SQLAlchemy`).
+- the persistence mechanism they offer (no persistence mechanism, :term:`ZODB`,
+ or :term:`SQLAlchemy`)
- the mechanism they use to map URLs to code (:term:`traversal` or :term:`URL
- dispatch`).
+ dispatch`)
The included scaffolds are these:
``starter``
- URL mapping via :term:`URL dispatch` and no persistence mechanism.
+ URL mapping via :term:`URL dispatch` and no persistence mechanism
``zodb``
- URL mapping via :term:`traversal` and persistence via :term:`ZODB`.
+ URL mapping via :term:`traversal` and persistence via :term:`ZODB`
``alchemy``
- URL mapping via :term:`URL dispatch` and persistence via
- :term:`SQLAlchemy`
+ URL mapping via :term:`URL dispatch` and persistence via :term:`SQLAlchemy`
.. index::
single: creating a project
@@ -64,13 +62,13 @@ The included scaffolds are these:
Creating the Project
--------------------
-In :ref:`installing_chapter`, you created a virtual Python environment via
-the ``virtualenv`` command. To start a :app:`Pyramid` :term:`project`, use
-the ``pcreate`` command installed within the virtualenv. We'll choose the
+In :ref:`installing_chapter`, you created a virtual Python environment via the
+``virtualenv`` command. To start a :app:`Pyramid` :term:`project`, use the
+``pcreate`` command installed within the virtualenv. We'll choose the
``starter`` scaffold for this purpose. When we invoke ``pcreate``, it will
create a directory that represents our project.
-In :ref:`installing_chapter` we called the virtualenv directory ``env``; the
+In :ref:`installing_chapter` we called the virtualenv directory ``env``. The
following commands assume that our current working directory is the ``env``
directory.
@@ -89,7 +87,6 @@ Or on Windows:
> %VENV%\Scripts\pcreate -s starter MyProject
-
Here's sample output from a run of ``pcreate`` on UNIX for a project we name
``MyProject``:
@@ -102,14 +99,14 @@ Here's sample output from a run of ``pcreate`` on UNIX for a project we name
Running /Users/chrism/projects/pyramid/bin/python setup.py egg_info
As a result of invoking the ``pcreate`` command, a directory named
-``MyProject`` is created. That directory is a :term:`project` directory.
-The ``setup.py`` file in that directory can be used to distribute your
-application, or install your application for deployment or development.
+``MyProject`` is created. That directory is a :term:`project` directory. The
+``setup.py`` file in that directory can be used to distribute your application,
+or install your application for deployment or development.
A ``.ini`` file named ``development.ini`` will be created in the project
-directory. You will use this ``.ini`` file to configure a server, to run
-your application, and to debug your application. It contains configuration
-that enables an interactive debugger and settings optimized for development.
+directory. You will use this ``.ini`` file to configure a server, to run your
+application, and to debug your application. It contains configuration that
+enables an interactive debugger and settings optimized for development.
Another ``.ini`` file named ``production.ini`` will also be created in the
project directory. It contains configuration that disables any interactive
@@ -118,28 +115,28 @@ number of debugging settings. You can use this file to put your application
into production.
The ``MyProject`` project directory contains an additional subdirectory named
-``myproject`` (note the case difference) representing a Python
-:term:`package` which holds very simple :app:`Pyramid` sample code. This is
-where you'll edit your application's Python code and templates.
-
-We created this project within an ``env`` virtualenv directory. However,
-note that this is not mandatory. The project directory can go more or less
-anywhere on your filesystem. You don't need to put it in a special "web
-server" directory, and you don't need to put it within a virtualenv
-directory. The author uses Linux mainly, and tends to put project
-directories which he creates within his ``~/projects`` directory. On
-Windows, it's a good idea to put project directories within a directory that
-contains no space characters, so it's wise to *avoid* a path that contains
-i.e. ``My Documents``. As a result, the author, when he uses Windows, just
-puts his projects in ``C:\projects``.
+``myproject`` (note the case difference) representing a Python :term:`package`
+which holds very simple :app:`Pyramid` sample code. This is where you'll edit
+your application's Python code and templates.
+
+We created this project within an ``env`` virtualenv directory. However, note
+that this is not mandatory. The project directory can go more or less anywhere
+on your filesystem. You don't need to put it in a special "web server"
+directory, and you don't need to put it within a virtualenv directory. The
+author uses Linux mainly, and tends to put project directories which he creates
+within his ``~/projects`` directory. On Windows, it's a good idea to put
+project directories within a directory that contains no space characters, so
+it's wise to *avoid* a path that contains, i.e., ``My Documents``. As a
+result, the author, when he uses Windows, just puts his projects in
+``C:\projects``.
.. warning::
You'll need to avoid using ``pcreate`` to create a project with the same
name as a Python standard library component. In particular, this means you
- should avoid using the names ``site`` or ``test``, both of which
- conflict with Python standard library packages. You should also avoid
- using the name ``pyramid``, which will conflict with Pyramid itself.
+ should avoid using the names ``site`` or ``test``, both of which conflict
+ with Python standard library packages. You should also avoid using the name
+ ``pyramid``, which will conflict with Pyramid itself.
.. index::
single: setup.py develop
@@ -154,10 +151,10 @@ newly created project directory and use the Python interpreter from the
command ``python setup.py develop``
The file named ``setup.py`` will be in the root of the pcreate-generated
-project directory. The ``python`` you're invoking should be the one that
-lives in the ``bin`` (or ``Scripts`` on Windows) directory of your virtual
-Python environment. Your terminal's current working directory *must* be the
-newly created project directory.
+project directory. The ``python`` you're invoking should be the one that lives
+in the ``bin`` (or ``Scripts`` on Windows) directory of your virtual Python
+environment. Your terminal's current working directory *must* be the newly
+created project directory.
On UNIX:
@@ -182,20 +179,20 @@ Elided output from a run of this command on UNIX is shown below:
...
Finished processing dependencies for MyProject==0.0
-This will install a :term:`distribution` representing your project
-into the virtual environment interpreter's library set so it can be
-found by ``import`` statements and by other console scripts such as
-``pserve``, ``pshell``, ``proutes`` and ``pviews``.
+This will install a :term:`distribution` representing your project into the
+virtual environment interpreter's library set so it can be found by ``import``
+statements and by other console scripts such as ``pserve``, ``pshell``,
+``proutes``, and ``pviews``.
.. index::
single: running tests
single: tests (running)
-Running The Tests For Your Application
+Running the Tests for Your Application
--------------------------------------
-To run unit tests for your application, you should invoke them using the
-Python interpreter from the :term:`virtualenv` you created during
+To run unit tests for your application, you should invoke them using the Python
+interpreter from the :term:`virtualenv` you created during
:ref:`installing_chapter` (the ``python`` command that lives in the ``bin``
directory of your virtualenv).
@@ -250,7 +247,7 @@ single sample test exists.
.. _running_the_project_application:
-Running The Project Application
+Running the Project Application
-------------------------------
Once a project is installed for development, you can run the application it
@@ -279,16 +276,16 @@ Here's sample output from a run of ``pserve`` on UNIX:
When you use ``pserve`` to start the application implied by the default
rendering of a scaffold, it will respond to requests on *all* IP addresses
-possessed by your system, not just requests to ``localhost``. This is what
-the ``0.0.0.0`` in ``serving on http://0.0.0.0:6543`` means. The server will
-respond to requests made to ``127.0.0.1`` and on any external IP address.
-For example, your system might be configured to have an external IP address
-``192.168.1.50``. If that's the case, if you use a browser running on the
-same system as Pyramid, it will be able to access the application via
-``http://127.0.0.1:6543/`` as well as via
-``http://192.168.1.50:6543/``. However, *other people* on other computers on
-the same network will also be able to visit your Pyramid application in their
-browser by visiting ``http://192.168.1.50:6543/``.
+possessed by your system, not just requests to ``localhost``. This is what the
+``0.0.0.0`` in ``serving on http://0.0.0.0:6543`` means. The server will
+respond to requests made to ``127.0.0.1`` and on any external IP address. For
+example, your system might be configured to have an external IP address
+``192.168.1.50``. If that's the case, if you use a browser running on the same
+system as Pyramid, it will be able to access the application via
+``http://127.0.0.1:6543/`` as well as via ``http://192.168.1.50:6543/``.
+However, *other people* on other computers on the same network will also be
+able to visit your Pyramid application in their browser by visiting
+``http://192.168.1.50:6543/``.
If you want to restrict access such that only a browser running on the same
machine as Pyramid will be able to access your Pyramid application, edit the
@@ -306,27 +303,26 @@ example:
You can change the port on which the server runs on by changing the same
portion of the ``development.ini`` file. For example, you can change the
``port = 6543`` line in the ``development.ini`` file's ``[server:main]``
-section to ``port = 8080`` to run the server on port 8080 instead of
-port 6543.
+section to ``port = 8080`` to run the server on port 8080 instead of port 6543.
-You can shut down a server started this way by pressing ``Ctrl-C``.
+You can shut down a server started this way by pressing ``Ctrl-C`` (or
+``Ctrl-Break`` on Windows).
The default server used to run your Pyramid application when a project is
-created from a scaffold is named :term:`Waitress`. This server is what
-prints the ``serving on...`` line when you run ``pserve``. It's a good idea
-to use this server during development, because it's very simple. It can also
-be used for light production. Setting your application up under a different
-server is not advised until you've done some development work under the
-default server, particularly if you're not yet experienced with Python web
-development. Python web server setup can be complex, and you should get some
-confidence that your application works in a default environment before trying
-to optimize it or make it "more like production". It's awfully easy to get
-sidetracked trying to set up a nondefault server for hours without actually
-starting to do any development. One of the nice things about Python web
-servers is that they're largely interchangeable, so if your application works
-under the default server, it will almost certainly work under any other
-server in production if you eventually choose to use a different one. Don't
-worry about it right now.
+created from a scaffold is named :term:`Waitress`. This server is what prints
+the ``serving on...`` line when you run ``pserve``. It's a good idea to use
+this server during development because it's very simple. It can also be used
+for light production. Setting your application up under a different server is
+not advised until you've done some development work under the default server,
+particularly if you're not yet experienced with Python web development. Python
+web server setup can be complex, and you should get some confidence that your
+application works in a default environment before trying to optimize it or make
+it "more like production". It's awfully easy to get sidetracked trying to set
+up a non-default server for hours without actually starting to do any
+development. One of the nice things about Python web servers is that they're
+largely interchangeable, so if your application works under the default server,
+it will almost certainly work under any other server in production if you
+eventually choose to use a different one. Don't worry about it right now.
For more detailed information about the startup process, see
:ref:`startup_chapter`. For more information about environment variables and
@@ -338,10 +334,10 @@ configuration file settings that influence startup and runtime behavior, see
Reloading Code
~~~~~~~~~~~~~~
-During development, it's often useful to run ``pserve`` using its
-``--reload`` option. When ``--reload`` is passed to ``pserve``, changes to
-any Python module your project uses will cause the server to restart. This
-typically makes development easier, as changes to Python code made within a
+During development, it's often useful to run ``pserve`` using its ``--reload``
+option. When ``--reload`` is passed to ``pserve``, changes to any Python
+module your project uses will cause the server to restart. This typically
+makes development easier, as changes to Python code made within a
:app:`Pyramid` application is not put into effect until the server restarts.
For example, on UNIX:
@@ -364,10 +360,10 @@ files, you'll see the server restart automatically:
serving on http://0.0.0.0:6543
Changes to template files (such as ``.pt`` or ``.mak`` files) won't cause the
-server to restart. Changes to template files don't require a server restart
-as long as the ``pyramid.reload_templates`` setting in the
-``development.ini`` file is ``true``. Changes made to template files when
-this setting is true will take effect immediately without a server restart.
+server to restart. Changes to template files don't require a server restart as
+long as the ``pyramid.reload_templates`` setting in the ``development.ini``
+file is ``true``. Changes made to template files when this setting is true
+will take effect immediately without a server restart.
.. index::
single: WSGI
@@ -392,25 +388,25 @@ generated ``starter`` application in a browser.
The Debug Toolbar
~~~~~~~~~~~~~~~~~
-If you click on the image shown at the right hand top of the page ("^DT"),
-you'll be presented with a debug toolbar that provides various niceties while
-you're developing. This image will float above every HTML page served by
-:app:`Pyramid` while you develop an application, and allows you show the
-toolbar as necessary. Click on ``Hide`` to hide the toolbar and show the
-image again.
+.. image:: project-show-toolbar.png
+
+If you click on the :app:`Pyramid` logo at the top right of the page, a new
+target window will open to present a debug toolbar that provides various
+niceties while you're developing. This logo will float above every HTML page
+served by :app:`Pyramid` while you develop an application, and allows you to
+show the toolbar as necessary.
.. image:: project-debug.png
-If you don't see the debug toolbar image on the right hand top of the page,
-it means you're browsing from a system that does not have debugging access.
-By default, for security reasons, only a browser originating from
-``localhost`` (``127.0.0.1``) can see the debug toolbar. To allow your
-browser on a remote system to access the server, add a line within the
-``[app:main]`` section of the ``development.ini`` file in the form
-``debugtoolbar.hosts = X.X.X.X``. For example, if your Pyramid application
-is running on a remote system, and you're browsing from a host with the IP
-address ``192.168.1.1``, you'd add something like this to enable the toolbar
-when your system contacts Pyramid:
+If you don't see the Pyramid logo on the top right of the page, it means you're
+browsing from a system that does not have debugging access. By default, for
+security reasons, only a browser originating from ``localhost`` (``127.0.0.1``)
+can see the debug toolbar. To allow your browser on a remote system to access
+the server, add a line within the ``[app:main]`` section of the
+``development.ini`` file in the form ``debugtoolbar.hosts = X .X.X.X``. For
+example, if your Pyramid application is running on a remote system, and you're
+browsing from a host with the IP address ``192.168.1.1``, you'd add something
+like this to enable the toolbar when your system contacts Pyramid:
.. code-block:: ini
@@ -422,9 +418,9 @@ For more information about what the debug toolbar allows you to do, see `the
documentation for pyramid_debugtoolbar
<http://docs.pylonsproject.org/projects/pyramid_debugtoolbar/en/latest/>`_.
-The debug toolbar will not be shown (and all debugging will be turned off)
-when you use the ``production.ini`` file instead of the ``development.ini``
-ini file to run the application.
+The debug toolbar will not be shown (and all debugging will be turned off) when
+you use the ``production.ini`` file instead of the ``development.ini`` ini file
+to run the application.
You can also turn the debug toolbar off by editing ``development.ini`` and
commenting out a line. For example, instead of:
@@ -450,9 +446,9 @@ Put a hash mark at the beginning of the ``pyramid_debugtoolbar`` line:
Then restart the application to see that the toolbar has been turned off.
Note that if you comment out the ``pyramid_debugtoolbar`` line, the ``#``
-*must* be in the first column. If you put it anywhere else,
-and then attempt to restart the application,
-you'll receive an error that ends something like this:
+*must* be in the first column. If you put it anywhere else, and then attempt
+to restart the application, you'll receive an error that ends something like
+this:
.. code-block:: text
@@ -469,9 +465,8 @@ which contains a Python :term:`package`. The package is *also* named
``myproject``, but it's lowercased; the scaffold generates a project which
contains a package that shares its name except for case.
-All :app:`Pyramid` ``pcreate`` -generated projects share a similar structure.
-The ``MyProject`` project we've generated has the following directory
-structure:
+All :app:`Pyramid` ``pcreate``-generated projects share a similar structure.
+The ``MyProject`` project we've generated has the following directory structure:
.. code-block:: text
@@ -497,29 +492,29 @@ structure:
The ``MyProject`` :term:`Project`
---------------------------------
-The ``MyProject`` :term:`project` directory is the distribution and
-deployment wrapper for your application. It contains both the ``myproject``
+The ``MyProject`` :term:`project` directory is the distribution and deployment
+wrapper for your application. It contains both the ``myproject``
:term:`package` representing your application as well as files used to
describe, run, and test your application.
-#. ``CHANGES.txt`` describes the changes you've made to the application. It
- is conventionally written in :term:`ReStructuredText` format.
+#. ``CHANGES.txt`` describes the changes you've made to the application. It is
+ conventionally written in :term:`ReStructuredText` format.
#. ``README.txt`` describes the application in general. It is conventionally
written in :term:`ReStructuredText` format.
-#. ``development.ini`` is a :term:`PasteDeploy` configuration file that can
- be used to execute your application during development.
+#. ``development.ini`` is a :term:`PasteDeploy` configuration file that can be
+ used to execute your application during development.
-#. ``production.ini`` is a :term:`PasteDeploy` configuration file that can
- be used to execute your application in a production configuration.
+#. ``production.ini`` is a :term:`PasteDeploy` configuration file that can be
+ used to execute your application in a production configuration.
#. ``MANIFEST.in`` is a :term:`distutils` "manifest" file, naming which files
should be included in a source distribution of the package when ``python
setup.py sdist`` is run.
-#. ``setup.py`` is the file you'll use to test and distribute your
- application. It is a standard :term:`setuptools` ``setup.py`` file.
+#. ``setup.py`` is the file you'll use to test and distribute your application.
+ It is a standard :term:`setuptools` ``setup.py`` file.
.. index::
single: PasteDeploy
@@ -530,9 +525,9 @@ describe, run, and test your application.
``development.ini``
~~~~~~~~~~~~~~~~~~~
-The ``development.ini`` file is a :term:`PasteDeploy` configuration file.
-Its purpose is to specify an application to run when you invoke ``pserve``,
-as well as the deployment settings provided to that application.
+The ``development.ini`` file is a :term:`PasteDeploy` configuration file. Its
+purpose is to specify an application to run when you invoke ``pserve``, as well
+as the deployment settings provided to that application.
The generated ``development.ini`` file looks like so:
@@ -541,47 +536,47 @@ The generated ``development.ini`` file looks like so:
:linenos:
This file contains several sections including ``[app:main]``,
-``[server:main]`` and several other sections related to logging
-configuration.
+``[server:main]``, and several other sections related to logging configuration.
The ``[app:main]`` section represents configuration for your :app:`Pyramid`
-application. The ``use`` setting is the only setting required to be present
-in the ``[app:main]`` section. Its default value, ``egg:MyProject``,
-indicates that our MyProject project contains the application that should be
-served. Other settings added to this section are passed as keyword arguments
-to the function named ``main`` in our package's ``__init__.py`` module. You
-can provide startup-time configuration parameters to your application by
-adding more settings to this section.
-
-.. note:: See :ref:`pastedeploy_entry_points` for more information about the
+application. The ``use`` setting is the only setting required to be present in
+the ``[app:main]`` section. Its default value, ``egg:MyProject``, indicates
+that our MyProject project contains the application that should be served.
+Other settings added to this section are passed as keyword arguments to the
+function named ``main`` in our package's ``__init__.py`` module. You can
+provide startup-time configuration parameters to your application by adding
+more settings to this section.
+
+.. seealso:: See :ref:`pastedeploy_entry_points` for more information about the
meaning of the ``use = egg:MyProject`` value in this section.
The ``pyramid.reload_templates`` setting in the ``[app:main]`` section is a
-:app:`Pyramid` -specific setting which is passed into the framework. If it
-exists, and its value is ``true``, supported template changes will not
-require an application restart to be detected. See
-:ref:`reload_templates_section` for more information.
+:app:`Pyramid`-specific setting which is passed into the framework. If it
+exists, and its value is ``true``, supported template changes will not require
+an application restart to be detected. See :ref:`reload_templates_section` for
+more information.
.. warning:: The ``pyramid.reload_templates`` option should be turned off for
production applications, as template rendering is slowed when it is turned
on.
-The ``pyramid.includes`` setting in the ``[app:main]`` section tells Pyramid
-to "include" configuration from another package. In this case, the line
+The ``pyramid.includes`` setting in the ``[app:main]`` section tells Pyramid to
+"include" configuration from another package. In this case, the line
``pyramid.includes = pyramid_debugtoolbar`` tells Pyramid to include
configuration from the ``pyramid_debugtoolbar`` package. This turns on a
-debugging panel in development mode which will be shown on the right hand
-side of the screen. Including the debug toolbar will also make it possible
-to interactively debug exceptions when an error occurs.
+debugging panel in development mode which can be opened by clicking on the
+:app:`Pyramid` logo on the top right of the screen. Including the debug
+toolbar will also make it possible to interactively debug exceptions when an
+error occurs.
-Various other settings may exist in this section having to do with debugging
-or influencing runtime behavior of a :app:`Pyramid` application. See
+Various other settings may exist in this section having to do with debugging or
+influencing runtime behavior of a :app:`Pyramid` application. See
:ref:`environment_chapter` for more information about these settings.
The name ``main`` in ``[app:main]`` signifies that this is the default
application run by ``pserve`` when it is invoked against this configuration
-file. The name ``main`` is a convention used by PasteDeploy signifying that
-it is the default application.
+file. The name ``main`` is a convention used by PasteDeploy signifying that it
+is the default application.
The ``[server:main]`` section of the configuration file configures a WSGI
server which listens on TCP port 6543. It is configured to listen on all
@@ -592,40 +587,38 @@ access to your system can see your Pyramid application.
The sections that live between the markers ``# Begin logging configuration``
and ``# End logging configuration`` represent Python's standard library
-:mod:`logging` module configuration for your application. The sections
-between these two markers are passed to the `logging module's config file
-configuration engine
-<http://docs.python.org/howto/logging.html#configuring-logging>`_ when the
-``pserve`` or ``pshell`` commands are executed. The default
-configuration sends application logging output to the standard error output
-of your terminal. For more information about logging configuration, see
-:ref:`logging_chapter`.
+:mod:`logging` module configuration for your application. The sections between
+these two markers are passed to the `logging module's config file configuration
+engine <http://docs.python.org/howto/logging.html#configuring-logging>`_ when
+the ``pserve`` or ``pshell`` commands are executed. The default configuration
+sends application logging output to the standard error output of your terminal.
+For more information about logging configuration, see :ref:`logging_chapter`.
See the :term:`PasteDeploy` documentation for more information about other
types of things you can put into this ``.ini`` file, such as other
-applications, :term:`middleware` and alternate :term:`WSGI` server
+applications, :term:`middleware`, and alternate :term:`WSGI` server
implementations.
.. index::
single: production.ini
``production.ini``
-~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~
-The ``production.ini`` file is a :term:`PasteDeploy` configuration file with
-a purpose much like that of ``development.ini``. However, it disables the
-debug toolbar, and filters all log messages except those above the WARN
-level. It also turns off template development options such that templates
-are not automatically reloaded when changed, and turns off all debugging
-options. This file is appropriate to use instead of ``development.ini`` when
-you put your application into production.
+The ``production.ini`` file is a :term:`PasteDeploy` configuration file with a
+purpose much like that of ``development.ini``. However, it disables the debug
+toolbar, and filters all log messages except those above the WARN level. It
+also turns off template development options such that templates are not
+automatically reloaded when changed, and turns off all debugging options. This
+file is appropriate to use instead of ``development.ini`` when you put your
+application into production.
It's important to use ``production.ini`` (and *not* ``development.ini``) to
benchmark your application and put it into production. ``development.ini``
configures your system with a debug toolbar that helps development, but the
inclusion of this toolbar slows down page rendering times by over an order of
-magnitude. The debug toolbar is also a potential security risk if you have
-it configured incorrectly.
+magnitude. The debug toolbar is also a potential security risk if you have it
+configured incorrectly.
.. index::
single: MANIFEST.in
@@ -637,42 +630,40 @@ The ``MANIFEST.in`` file is a :term:`distutils` configuration file which
specifies the non-Python files that should be included when a
:term:`distribution` of your Pyramid project is created when you run ``python
setup.py sdist``. Due to the information contained in the default
-``MANIFEST.in``, an sdist of your Pyramid project will include ``.txt``
-files, ``.ini`` files, ``.rst`` files, graphics files, and template files, as
-well as ``.py`` files. See
+``MANIFEST.in``, an sdist of your Pyramid project will include ``.txt`` files,
+``.ini`` files, ``.rst`` files, graphics files, and template files, as well as
+``.py`` files. See
http://docs.python.org/distutils/sourcedist.html#the-manifest-in-template for
more information about the syntax and usage of ``MANIFEST.in``.
-Without the presence of a ``MANIFEST.in`` file or without checking your
-source code into a version control repository, ``setup.py sdist`` places only
-*Python source files* (files ending with a ``.py`` extension) into tarballs
-generated by ``python setup.py sdist``. This means, for example, if your
-project was not checked into a setuptools-compatible source control system,
-and your project directory didn't contain a ``MANIFEST.in`` file that told
-the ``sdist`` machinery to include ``*.pt`` files, the
-``myproject/templates/mytemplate.pt`` file would not be included in the
-generated tarball.
-
-Projects generated by Pyramid scaffolds include a default ``MANIFEST.in``
-file. The ``MANIFEST.in`` file contains declarations which tell it to
-include files like ``*.pt``, ``*.css`` and ``*.js`` in the generated tarball.
-If you include files with extensions other than the files named in the
-project's ``MANIFEST.in`` and you don't make use of a setuptools-compatible
-version control system, you'll need to edit the ``MANIFEST.in`` file and
-include the statements necessary to include your new files. See
-http://docs.python.org/distutils/sourcedist.html#principle for more
-information about how to do this.
-
-You can also delete ``MANIFEST.in`` from your project and rely on a
-setuptools feature which simply causes all files checked into a version
-control system to be put into the generated tarball. To allow this to
-happen, check all the files that you'd like to be distributed along with your
-application's Python files into Subversion. After you do this, when you
-rerun ``setup.py sdist``, all files checked into the version control system
-will be included in the tarball. If you don't use Subversion, and instead
-use a different version control system, you may need to install a setuptools
-add-on such as ``setuptools-git`` or ``setuptools-hg`` for this behavior to
-work properly.
+Without the presence of a ``MANIFEST.in`` file or without checking your source
+code into a version control repository, ``setup.py sdist`` places only *Python
+source files* (files ending with a ``.py`` extension) into tarballs generated
+by ``python setup.py sdist``. This means, for example, if your project was not
+checked into a setuptools-compatible source control system, and your project
+directory didn't contain a ``MANIFEST.in`` file that told the ``sdist``
+machinery to include ``*.pt`` files, the ``myproject/templates/mytemplate.pt``
+file would not be included in the generated tarball.
+
+Projects generated by Pyramid scaffolds include a default ``MANIFEST.in`` file.
+The ``MANIFEST.in`` file contains declarations which tell it to include files
+like ``*.pt``, ``*.css`` and ``*.js`` in the generated tarball. If you include
+files with extensions other than the files named in the project's
+``MANIFEST.in`` and you don't make use of a setuptools-compatible version
+control system, you'll need to edit the ``MANIFEST.in`` file and include the
+statements necessary to include your new files. See
+http://docs.python.org/distutils/sourcedist.html#principle for more information
+about how to do this.
+
+You can also delete ``MANIFEST.in`` from your project and rely on a setuptools
+feature which simply causes all files checked into a version control system to
+be put into the generated tarball. To allow this to happen, check all the
+files that you'd like to be distributed along with your application's Python
+files into Subversion. After you do this, when you rerun ``setup.py sdist``,
+all files checked into the version control system will be included in the
+tarball. If you don't use Subversion, and instead use a different version
+control system, you may need to install a setuptools add-on such as
+``setuptools-git`` or ``setuptools-hg`` for this behavior to work properly.
.. index::
single: setup.py
@@ -686,11 +677,11 @@ testing, packaging, and distributing your application.
.. note::
- ``setup.py`` is the de facto standard which Python developers use to
- distribute their reusable code. You can read more about ``setup.py`` files
- and their usage in the `Setuptools documentation
- <http://peak.telecommunity.com/DevCenter/setuptools>`_ and `The
- Hitchhiker's Guide to Packaging <http://guide.python-distribute.org/>`_.
+ ``setup.py`` is the de facto standard which Python developers use to
+ distribute their reusable code. You can read more about ``setup.py`` files
+ and their usage in the `Setuptools documentation
+ <http://peak.telecommunity.com/DevCenter/setuptools>`_ and `The Hitchhiker's
+ Guide to Packaging <http://guide.python-distribute.org/>`_.
Our generated ``setup.py`` looks like this:
@@ -699,47 +690,47 @@ Our generated ``setup.py`` looks like this:
:linenos:
The ``setup.py`` file calls the setuptools ``setup`` function, which does
-various things depending on the arguments passed to ``setup.py`` on the
-command line.
+various things depending on the arguments passed to ``setup.py`` on the command
+line.
-Within the arguments to this function call, information about your
-application is kept. While it's beyond the scope of this documentation to
-explain everything about setuptools setup files, we'll provide a whirlwind
-tour of what exists in this file in this section.
+Within the arguments to this function call, information about your application
+is kept. While it's beyond the scope of this documentation to explain
+everything about setuptools setup files, we'll provide a whirlwind tour of what
+exists in this file in this section.
Your application's name can be any string; it is specified in the ``name``
field. The version number is specified in the ``version`` value. A short
-description is provided in the ``description`` field. The
-``long_description`` is conventionally the content of the README and CHANGES
-file appended together. The ``classifiers`` field is a list of `Trove
+description is provided in the ``description`` field. The ``long_description``
+is conventionally the content of the README and CHANGES file appended together.
+The ``classifiers`` field is a list of `Trove
<http://pypi.python.org/pypi?%3Aaction=list_classifiers>`_ classifiers
describing your application. ``author`` and ``author_email`` are text fields
which probably don't need any description. ``url`` is a field that should
-point at your application project's URL (if any).
-``packages=find_packages()`` causes all packages within the project to be
-found when packaging the application. ``include_package_data`` will include
-non-Python files when the application is packaged if those files are checked
-into version control. ``zip_safe`` indicates that this package is not safe
-to use as a zipped egg; instead it will always unpack as a directory, which
-is more convenient. ``install_requires`` and ``tests_require`` indicate that
-this package depends on the ``pyramid`` package. ``test_suite`` points at
-the package for our application, which means all tests found in the package
-will be run when ``setup.py test`` is invoked. We examined ``entry_points``
-in our discussion of the ``development.ini`` file; this file defines the
-``main`` entry point that represents our project's application.
-
-Usually you only need to think about the contents of the ``setup.py`` file
-when distributing your application to other people, when adding Python
-package dependencies, or when versioning your application for your own use.
-For fun, you can try this command now:
+point at your application project's URL (if any). ``packages=find_packages()``
+causes all packages within the project to be found when packaging the
+application. ``include_package_data`` will include non-Python files when the
+application is packaged if those files are checked into version control.
+``zip_safe`` indicates that this package is not safe to use as a zipped egg;
+instead it will always unpack as a directory, which is more convenient.
+``install_requires`` and ``tests_require`` indicate that this package depends
+on the ``pyramid`` package. ``test_suite`` points at the package for our
+application, which means all tests found in the package will be run when
+``setup.py test`` is invoked. We examined ``entry_points`` in our discussion
+of the ``development.ini`` file; this file defines the ``main`` entry point
+that represents our project's application.
+
+Usually you only need to think about the contents of the ``setup.py`` file when
+distributing your application to other people, when adding Python package
+dependencies, or when versioning your application for your own use. For fun,
+you can try this command now:
.. code-block:: text
- $ python setup.py sdist
+ $ $VENV/bin/python setup.py sdist
-This will create a tarball of your application in a ``dist`` subdirectory
-named ``MyProject-0.1.tar.gz``. You can send this tarball to other people
-who want to install and use your application.
+This will create a tarball of your application in a ``dist`` subdirectory named
+``MyProject-0.1.tar.gz``. You can send this tarball to other people who want
+to install and use your application.
.. index::
single: package
@@ -750,25 +741,22 @@ The ``myproject`` :term:`Package`
The ``myproject`` :term:`package` lives inside the ``MyProject``
:term:`project`. It contains:
-#. An ``__init__.py`` file signifies that this is a Python :term:`package`.
- It also contains code that helps users run the application, including a
+#. An ``__init__.py`` file signifies that this is a Python :term:`package`. It
+ also contains code that helps users run the application, including a
``main`` function which is used as a entry point for commands such as
``pserve``, ``pshell``, ``pviews``, and others.
-#. A ``templates`` directory, which contains :term:`Chameleon` (or
- other types of) templates.
+#. A ``templates`` directory, which contains :term:`Chameleon` (or other types
+ of) templates.
-#. A ``tests.py`` module, which contains unit test code for the
- application.
+#. A ``tests.py`` module, which contains unit test code for the application.
-#. A ``views.py`` module, which contains view code for the
- application.
+#. A ``views.py`` module, which contains view code for the application.
-These are purely conventions established by the scaffold:
-:app:`Pyramid` doesn't insist that you name things in any particular way.
-However, it's generally a good idea to follow Pyramid standards for naming,
-so that other Pyramid developers can get up to speed quickly on your code
-when you need help.
+These are purely conventions established by the scaffold. :app:`Pyramid`
+doesn't insist that you name things in any particular way. However, it's
+generally a good idea to follow Pyramid standards for naming, so that other
+Pyramid developers can get up to speed quickly on your code when you need help.
.. index::
single: __init__.py
@@ -802,11 +790,11 @@ also informs Python that the directory which contains it is a *package*.
specify renderers with the ``.pt`` extension.
Line 9 registers a static view, which will serve up the files from the
- ``myproject:static`` :term:`asset specification` (the ``static``
- directory of the ``myproject`` package).
+ ``myproject:static`` :term:`asset specification` (the ``static`` directory
+ of the ``myproject`` package).
- Line 10 adds a :term:`route` to the configuration. This route is later
- used by a view in the ``views`` module.
+ Line 10 adds a :term:`route` to the configuration. This route is later used
+ by a view in the ``views`` module.
Line 11 calls ``config.scan()``, which picks up view registrations declared
elsewhere in the package (in this case, in the ``views.py`` module).
@@ -822,64 +810,63 @@ also informs Python that the directory which contains it is a *package*.
Much of the heavy lifting in a :app:`Pyramid` application is done by *view
callables*. A :term:`view callable` is the main tool of a :app:`Pyramid` web
-application developer; it is a bit of code which accepts a :term:`request`
-and which returns a :term:`response`.
+application developer; it is a bit of code which accepts a :term:`request` and
+which returns a :term:`response`.
.. literalinclude:: MyProject/myproject/views.py
:language: python
:linenos:
Lines 4-6 define and register a :term:`view callable` named ``my_view``. The
-function named ``my_view`` is decorated with a ``view_config`` decorator
-(which is processed by the ``config.scan()`` line in our ``__init__.py``).
-The view_config decorator asserts that this view be found when a
-:term:`route` named ``home`` is matched. In our case, because our
-``__init__.py`` maps the route named ``home`` to the URL pattern ``/``, this
-route will match when a visitor visits the root URL. The view_config
-decorator also names a ``renderer``, which in this case is a template that
-will be used to render the result of the view callable. This particular view
-declaration points at ``templates/mytemplate.pt``, which is a :term:`asset
-specification` that specifies the ``mytemplate.pt`` file within the
-``templates`` directory of the ``myproject`` package. The asset
-specification could have also been specified as
-``myproject:templates/mytemplate.pt``; the leading package name and colon is
-optional. The template file pointed to is a :term:`Chameleon` ZPT
-template file (``templates/my_template.pt``).
+function named ``my_view`` is decorated with a ``view_config`` decorator (which
+is processed by the ``config.scan()`` line in our ``__init__.py``). The
+view_config decorator asserts that this view be found when a :term:`route`
+named ``home`` is matched. In our case, because our ``__init__.py`` maps the
+route named ``home`` to the URL pattern ``/``, this route will match when a
+visitor visits the root URL. The view_config decorator also names a
+``renderer``, which in this case is a template that will be used to render the
+result of the view callable. This particular view declaration points at
+``templates/mytemplate.pt``, which is an :term:`asset specification` that
+specifies the ``mytemplate.pt`` file within the ``templates`` directory of the
+``myproject`` package. The asset specification could have also been specified
+as ``myproject:templates/mytemplate.pt``; the leading package name and colon is
+optional. The template file pointed to is a :term:`Chameleon` ZPT template
+file (``templates/my_template.pt``).
This view callable function is handed a single piece of information: the
-:term:`request`. The *request* is an instance of the :term:`WebOb`
-``Request`` class representing the browser's request to our server.
+:term:`request`. The *request* is an instance of the :term:`WebOb` ``Request``
+class representing the browser's request to our server.
This view is configured to invoke a :term:`renderer` on a template. The
dictionary the view returns (on line 6) provides the value the renderer
-substitutes into the template when generating HTML. The renderer then
-returns the HTML in a :term:`response`.
+substitutes into the template when generating HTML. The renderer then returns
+the HTML in a :term:`response`.
.. note:: Dictionaries provide values to :term:`template`\s.
.. note:: When the application is run with the scaffold's :ref:`default
- development.ini <MyProject_ini>` configuration :ref:`logging is set up
+ development.ini <MyProject_ini>` configuration, :ref:`logging is set up
<MyProject_ini_logging>` to aid debugging. If an exception is raised,
uncaught tracebacks are displayed after the startup messages on :ref:`the
console running the server <running_the_project_application>`. Also
- ``print()`` statements may be inserted into the application for debugging
- to send output to this console.
+ ``print()`` statements may be inserted into the application for debugging to
+ send output to this console.
.. note:: ``development.ini`` has a setting that controls how templates are
reloaded, ``pyramid.reload_templates``.
- - When set to ``True`` (as in the scaffold ``development.ini``) changed
+ - When set to ``True`` (as in the scaffold ``development.ini``), changed
templates automatically reload without a server restart. This is
convenient while developing, but slows template rendering speed.
- - When set to ``False`` (the default value), changing templates requires
- a server restart to reload them. Production applications should use
+ - When set to ``False`` (the default value), changing templates requires a
+ server restart to reload them. Production applications should use
``pyramid.reload_templates = False``.
.. seealso::
- See also :ref:`views_which_use_a_renderer` for more information
- about how views, renderers, and templates relate and cooperate.
+ See also :ref:`views_which_use_a_renderer` for more information about how
+ views, renderers, and templates relate and cooperate.
.. seealso::
@@ -905,10 +892,10 @@ template. It includes CSS and images.
``templates/mytemplate.pt``
~~~~~~~~~~~~~~~~~~~~~~~~~~~
-The single :term:`Chameleon` template that exists in the project. Its
+This is the single :term:`Chameleon` template that exists in the project. Its
contents are too long to show here, but it displays a default page when
-rendered. It is referenced by the call to ``@view_config`` as the
-``renderer`` of the ``my_view`` view callable in the ``views.py`` file. See
+rendered. It is referenced by the call to ``@view_config`` as the ``renderer``
+of the ``my_view`` view callable in the ``views.py`` file. See
:ref:`views_which_use_a_renderer` for more information about renderers.
Templates are accessed and used by view configurations and sometimes by view
@@ -925,13 +912,13 @@ The ``tests.py`` module includes unit tests for your application.
.. literalinclude:: MyProject/myproject/tests.py
:language: python
+ :lines: 1-18
:linenos:
This sample ``tests.py`` file has a single unit test defined within it. This
-test is executed when you run ``python setup.py test``. You may add more
-tests here as you build your application. You are not required to write
-tests to use :app:`Pyramid`, this file is simply provided as convenience and
-example.
+test is executed when you run ``python setup.py test``. You may add more tests
+here as you build your application. You are not required to write tests to use
+:app:`Pyramid`. This file is simply provided for convenience and example.
See :ref:`testing_chapter` for more information about writing :app:`Pyramid`
unit tests.
@@ -942,30 +929,30 @@ unit tests.
.. _modifying_package_structure:
Modifying Package Structure
-----------------------------
+---------------------------
It is best practice for your application's code layout to not stray too much
-from accepted Pyramid scaffold defaults. If you refrain from changing
-things very much, other Pyramid coders will be able to more quickly
-understand your application. However, the code layout choices made for you
-by a scaffold are in no way magical or required. Despite the choices
-made for you by any scaffold, you can decide to lay your code out any
-way you see fit.
+from accepted Pyramid scaffold defaults. If you refrain from changing things
+very much, other Pyramid coders will be able to more quickly understand your
+application. However, the code layout choices made for you by a scaffold are
+in no way magical or required. Despite the choices made for you by any
+scaffold, you can decide to lay your code out any way you see fit.
For example, the configuration method named
:meth:`~pyramid.config.Configurator.add_view` requires you to pass a
:term:`dotted Python name` or a direct object reference as the class or
-function to be used as a view. By default, the ``starter`` scaffold would
-have you add view functions to the ``views.py`` module in your package.
-However, you might be more comfortable creating a ``views`` *directory*, and
-adding a single file for each view.
+function to be used as a view. By default, the ``starter`` scaffold would have
+you add view functions to the ``views.py`` module in your package. However, you
+might be more comfortable creating a ``views`` *directory*, and adding a single
+file for each view.
If your project package name was ``myproject`` and you wanted to arrange all
your views in a Python subpackage within the ``myproject`` :term:`package`
-named ``views`` instead of within a single ``views.py`` file, you might:
+named ``views`` instead of within a single ``views.py`` file, you might do the
+following.
-- Create a ``views`` directory inside your ``myproject`` package directory
- (the same directory which holds ``views.py``).
+- Create a ``views`` directory inside your ``myproject`` package directory (the
+ same directory which holds ``views.py``).
- Create a file within the new ``views`` directory named ``__init__.py``. (It
can be empty. This just tells Python that the ``views`` directory is a
@@ -977,72 +964,70 @@ named ``views`` instead of within a single ``views.py`` file, you might:
specification` values in ``blog.py`` must now be fully qualified with the
project's package name (``myproject:templates/blog.pt``).
-You can then continue to add view callable functions to the ``blog.py``
-module, but you can also add other ``.py`` files which contain view callable
-functions to the ``views`` directory. As long as you use the
-``@view_config`` directive to register views in conjunction with
-``config.scan()`` they will be picked up automatically when the application
-is restarted.
+You can then continue to add view callable functions to the ``blog.py`` module,
+but you can also add other ``.py`` files which contain view callable functions
+to the ``views`` directory. As long as you use the ``@view_config`` directive
+to register views in conjunction with ``config.scan()``, they will be picked up
+automatically when the application is restarted.
Using the Interactive Shell
---------------------------
It is possible to use the ``pshell`` command to load a Python interpreter
-prompt with a similar configuration as would be loaded if you were running
-your Pyramid application via ``pserve``. This can be a useful debugging tool.
-See :ref:`interactive_shell` for more details.
+prompt with a similar configuration as would be loaded if you were running your
+Pyramid application via ``pserve``. This can be a useful debugging tool. See
+:ref:`interactive_shell` for more details.
.. _what_is_this_pserve_thing:
What Is This ``pserve`` Thing
-----------------------------
-The code generated by an :app:`Pyramid` scaffold assumes that you will be
-using the ``pserve`` command to start your application while you do
-development. ``pserve`` is a command that reads a :term:`PasteDeploy`
-``.ini`` file (e.g. ``development.ini``) and configures a server to serve a
-Pyramid application based on the data in the file.
+The code generated by a :app:`Pyramid` scaffold assumes that you will be using
+the ``pserve`` command to start your application while you do development.
+``pserve`` is a command that reads a :term:`PasteDeploy` ``.ini`` file (e.g.,
+``development.ini``), and configures a server to serve a :app:`Pyramid`
+application based on the data in the file.
``pserve`` is by no means the only way to start up and serve a :app:`Pyramid`
application. As we saw in :ref:`firstapp_chapter`, ``pserve`` needn't be
invoked at all to run a :app:`Pyramid` application. The use of ``pserve`` to
-run a :app:`Pyramid` application is purely conventional based on the output
-of its scaffolding. But we strongly recommend using ``pserve`` while
-developing your application, because many other convenience introspection
-commands (such as ``pviews``, ``prequest``, ``proutes`` and others) are also
-implemented in terms of configuration availability of this ``.ini`` file
-format. It also configures Pyramid logging and provides the ``--reload``
-switch for convenient restarting of the server when code changes.
+run a :app:`Pyramid` application is purely conventional based on the output of
+its scaffolding. But we strongly recommend using ``pserve`` while developing
+your application because many other convenience introspection commands (such as
+``pviews``, ``prequest``, ``proutes``, and others) are also implemented in
+terms of configuration availability of this ``.ini`` file format. It also
+configures Pyramid logging and provides the ``--reload`` switch for convenient
+restarting of the server when code changes.
.. _alternate_wsgi_server:
Using an Alternate WSGI Server
------------------------------
-Pyramid scaffolds generate projects which use the :term:`Waitress` WSGI
-server. Waitress is a server that is suited for development and light
-production usage. It's not the fastest nor the most featureful WSGI server.
-Instead, its main feature is that it works on all platforms that Pyramid
-needs to run on, making it a good choice as a default server from the
-perspective of Pyramid's developers.
+Pyramid scaffolds generate projects which use the :term:`Waitress` WSGI server.
+Waitress is a server that is suited for development and light production
+usage. It's not the fastest nor the most featureful WSGI server. Instead, its
+main feature is that it works on all platforms that Pyramid needs to run on,
+making it a good choice as a default server from the perspective of Pyramid's
+developers.
Any WSGI server is capable of running a :app:`Pyramid` application. But we
-suggest you stick with the default server for development, and that you wait
-to investigate other server options until you're ready to deploy your
-application to production. Unless for some reason you need to develop on a
-non-local system, investigating alternate server options is usually a
-distraction until you're ready to deploy. But we recommend developing using
-the default configuration on a local system that you have complete control
-over; it will provide the best development experience.
+suggest you stick with the default server for development, and that you wait to
+investigate other server options until you're ready to deploy your application
+to production. Unless for some reason you need to develop on a non-local
+system, investigating alternate server options is usually a distraction until
+you're ready to deploy. But we recommend developing using the default
+configuration on a local system that you have complete control over; it will
+provide the best development experience.
One popular production alternative to the default Waitress server is
-:term:`mod_wsgi`. You can use mod_wsgi to serve your :app:`Pyramid`
-application using the Apache web server rather than any "pure-Python" server
-like Waitress. It is fast and featureful. See :ref:`modwsgi_tutorial` for
-details.
+:term:`mod_wsgi`. You can use mod_wsgi to serve your :app:`Pyramid` application
+using the Apache web server rather than any "pure-Python" server like Waitress.
+It is fast and featureful. See :ref:`modwsgi_tutorial` for details.
Another good production alternative is :term:`Green Unicorn` (aka
-``gunicorn``). It's faster than Waitress and slightly easier to configure
-than mod_wsgi, although it depends, in its default configuration, on having a
-buffering HTTP proxy in front of it. It does not, as of this writing, work
-on Windows.
+``gunicorn``). It's faster than Waitress and slightly easier to configure than
+mod_wsgi, although it depends, in its default configuration, on having a
+buffering HTTP proxy in front of it. It does not, as of this writing, work on
+Windows.
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 <example_render_to_response_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
-<http://en.wikipedia.org/wiki/JSONP>`_ renderer factory helper which
-implements a hybrid json/jsonp renderer. JSONP is useful for making
-cross-domain AJAX requests.
+<http://en.wikipedia.org/wiki/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
+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
<http://api.jquery.com/jQuery.ajax/>`_.
-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 <automatic_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.
diff --git a/docs/narr/router.rst b/docs/narr/router.rst
index 6f90c70cc..e02142e6e 100644
--- a/docs/narr/router.rst
+++ b/docs/narr/router.rst
@@ -17,12 +17,12 @@ requests and return responses. What happens from the time a :term:`WSGI`
request enters a :app:`Pyramid` application through to the point that
:app:`Pyramid` hands off a response back to WSGI for upstream processing?
-#. A user initiates a request from his browser to the hostname and port
+#. A user initiates a request from their browser to the hostname and port
number of the WSGI server used by the :app:`Pyramid` application.
#. The WSGI server used by the :app:`Pyramid` application passes the WSGI
- environment to the ``__call__`` method of the :app:`Pyramid`
- :term:`router` object.
+ environment to the ``__call__`` method of the :app:`Pyramid` :term:`router`
+ object.
#. A :term:`request` object is created based on the WSGI environment.
@@ -35,41 +35,40 @@ request enters a :app:`Pyramid` application through to the point that
#. A :class:`~pyramid.events.NewRequest` :term:`event` is sent to any
subscribers.
-#. If any :term:`route` has been defined within application configuration,
- the :app:`Pyramid` :term:`router` calls a :term:`URL dispatch` "route
- mapper." The job of the mapper is to examine the request to determine
- whether any user-defined :term:`route` matches the current WSGI
- environment. The :term:`router` passes the request as an argument to the
- mapper.
+#. If any :term:`route` has been defined within application configuration, the
+ :app:`Pyramid` :term:`router` calls a :term:`URL dispatch` "route mapper."
+ The job of the mapper is to examine the request to determine whether any
+ user-defined :term:`route` matches the current WSGI environment. The
+ :term:`router` passes the request as an argument to the mapper.
#. If any route matches, the route mapper adds attributes to the request:
``matchdict`` and ``matched_route`` attributes are added to the request
object. The former contains a dictionary representing the matched dynamic
- elements of the request's ``PATH_INFO`` value, the latter contains the
+ elements of the request's ``PATH_INFO`` value, and the latter contains the
:class:`~pyramid.interfaces.IRoute` object representing the route which
- matched. The root object associated with the route found is also
- generated: if the :term:`route configuration` which matched has an
- associated ``factory`` argument, this factory is used to generate the
- root object, otherwise a default :term:`root factory` is used.
-
-#. If a route match was *not* found, and a ``root_factory`` argument was
- passed to the :term:`Configurator` constructor, that callable is used to
- generate the root object. If the ``root_factory`` argument passed to the
+ matched. The root object associated with the route found is also generated:
+ if the :term:`route configuration` which matched has an associated
+ ``factory`` argument, this factory is used to generate the root object,
+ otherwise a default :term:`root factory` is used.
+
+#. If a route match was *not* found, and a ``root_factory`` argument was passed
+ to the :term:`Configurator` constructor, that callable is used to generate
+ the root object. If the ``root_factory`` argument passed to the
Configurator constructor was ``None``, a default root factory is used to
generate a root object.
-#. The :app:`Pyramid` router calls a "traverser" function with the root
- object and the request. The traverser function attempts to traverse the
- root object (using any existing ``__getitem__`` on the root object and
+#. The :app:`Pyramid` router calls a "traverser" function with the root object
+ and the request. The traverser function attempts to traverse the root
+ object (using any existing ``__getitem__`` on the root object and
subobjects) to find a :term:`context`. If the root object has no
- ``__getitem__`` method, the root itself is assumed to be the context. The
+ ``__getitem__`` method, the root itself is assumed to be the context. The
exact traversal algorithm is described in :ref:`traversal_chapter`. The
traverser function returns a dictionary, which contains a :term:`context`
and a :term:`view name` as well as other ancillary information.
#. The request is decorated with various names returned from the traverser
- (such as ``context``, ``view_name``, and so forth), so they can be
- accessed via e.g. ``request.context`` within :term:`view` code.
+ (such as ``context``, ``view_name``, and so forth), so they can be accessed
+ via, for example, ``request.context`` within :term:`view` code.
#. A :class:`~pyramid.events.ContextFound` :term:`event` is sent to any
subscribers.
@@ -87,34 +86,33 @@ request enters a :app:`Pyramid` application through to the point that
protected by a :term:`permission`, :app:`Pyramid` determines whether the
view callable being asked for can be executed by the requesting user based
on credential information in the request and security information attached
- to the context. If the view execution is allowed, :app:`Pyramid` calls
- the view callable to obtain a response. If view execution is forbidden,
+ to the context. If the view execution is allowed, :app:`Pyramid` calls the
+ view callable to obtain a response. If view execution is forbidden,
:app:`Pyramid` raises a :class:`~pyramid.httpexceptions.HTTPForbidden`
exception.
#. If any exception is raised within a :term:`root factory`, by
- :term:`traversal`, by a :term:`view callable` or by :app:`Pyramid` itself
+ :term:`traversal`, by a :term:`view callable`, or by :app:`Pyramid` itself
(such as when it raises :class:`~pyramid.httpexceptions.HTTPNotFound` or
:class:`~pyramid.httpexceptions.HTTPForbidden`), the router catches the
exception, and attaches it to the request as the ``exception`` attribute.
- It then attempts to find a :term:`exception view` for the exception that
- was caught. If it finds an exception view callable, that callable is
- called, and is presumed to generate a response. If an :term:`exception
- view` that matches the exception cannot be found, the exception is
- reraised.
-
-#. The following steps occur only when a :term:`response` could be
- successfully generated by a normal :term:`view callable` or an
- :term:`exception view` callable. :app:`Pyramid` will attempt to execute
- any :term:`response callback` functions attached via
- :meth:`~pyramid.request.Request.add_response_callback`. A
+ It then attempts to find a :term:`exception view` for the exception that was
+ caught. If it finds an exception view callable, that callable is called,
+ and is presumed to generate a response. If an :term:`exception view` that
+ matches the exception cannot be found, the exception is reraised.
+
+#. The following steps occur only when a :term:`response` could be successfully
+ generated by a normal :term:`view callable` or an :term:`exception view`
+ callable. :app:`Pyramid` will attempt to execute any :term:`response
+ callback` functions attached via
+ :meth:`~pyramid.request.Request.add_response_callback`. A
:class:`~pyramid.events.NewResponse` :term:`event` is then sent to any
subscribers. The response object's ``__call__`` method is then used to
generate a WSGI response. The response is sent back to the upstream WSGI
server.
-#. :app:`Pyramid` will attempt to execute any :term:`finished
- callback` functions attached via
+#. :app:`Pyramid` will attempt to execute any :term:`finished callback`
+ functions attached via
:meth:`~pyramid.request.Request.add_finished_callback`.
#. The :term:`thread local` stack is popped.
@@ -123,7 +121,6 @@ request enters a :app:`Pyramid` application through to the point that
:alt: Pyramid Router
This is a very high-level overview that leaves out various details. For more
-detail about subsystems invoked by the :app:`Pyramid` router such as
+detail about subsystems invoked by the :app:`Pyramid` router, such as
traversal, URL dispatch, views, and event processing, see
:ref:`urldispatch_chapter`, :ref:`views_chapter`, and :ref:`events_chapter`.
-
diff --git a/docs/narr/startup.rst b/docs/narr/startup.rst
index a1a23ed52..485f6b181 100644
--- a/docs/narr/startup.rst
+++ b/docs/narr/startup.rst
@@ -12,10 +12,9 @@ you'll see something much like this show up on the console:
Starting server in PID 16601.
serving on 0.0.0.0:6543 view at http://127.0.0.1:6543
-This chapter explains what happens between the time you press the "Return"
-key on your keyboard after typing ``pserve development.ini``
-and the time the line ``serving on 0.0.0.0:6543 ...`` is output to your
-console.
+This chapter explains what happens between the time you press the "Return" key
+on your keyboard after typing ``pserve development.ini`` and the time the line
+``serving on 0.0.0.0:6543 ...`` is output to your console.
.. index::
single: startup process
@@ -27,9 +26,8 @@ The Startup Process
The easiest and best-documented way to start and serve a :app:`Pyramid`
application is to use the ``pserve`` command against a :term:`PasteDeploy`
``.ini`` file. This uses the ``.ini`` file to infer settings and starts a
-server listening on a port. For the purposes of this discussion, we'll
-assume that you are using this command to run your :app:`Pyramid`
-application.
+server listening on a port. For the purposes of this discussion, we'll assume
+that you are using this command to run your :app:`Pyramid` application.
Here's a high-level time-ordered overview of what happens when you press
``return`` after running ``pserve development.ini``.
@@ -41,30 +39,29 @@ Here's a high-level time-ordered overview of what happens when you press
#. The framework finds a section named either ``[app:main]``,
``[pipeline:main]``, or ``[composite:main]`` in the ``.ini`` file. This
- section represents the configuration of a :term:`WSGI` application that
- will be served. If you're using a simple application (e.g.
- ``[app:main]``), the application's ``paste.app_factory`` :term:`entry
- point` will be named on the ``use=`` line within the section's
- configuration. If, instead of a simple application, you're using a WSGI
- :term:`pipeline` (e.g. a ``[pipeline:main]`` section), the application
- named on the "last" element will refer to your :app:`Pyramid` application.
- If instead of a simple application or a pipeline, you're using a
- "composite" (e.g. ``[composite:main]``), refer to the documentation for
- that particular composite to understand how to make it refer to your
- :app:`Pyramid` application. In most cases, a Pyramid application built
- from a scaffold will have a single ``[app:main]`` section in it, and this
- will be the application served.
-
-#. The framework finds all :mod:`logging` related configuration in the
- ``.ini`` file and uses it to configure the Python standard library logging
- system for this application. See :ref:`logging_config` for more
- information.
-
-#. The application's *constructor* named by the entry point reference on the
- ``use=`` line of the section representing your :app:`Pyramid` application
- is passed the key/value parameters mentioned within the section in which
- it's defined. The constructor is meant to return a :term:`router`
- instance, which is a :term:`WSGI` application.
+ section represents the configuration of a :term:`WSGI` application that will
+ be served. If you're using a simple application (e.g., ``[app:main]``), the
+ application's ``paste.app_factory`` :term:`entry point` will be named on the
+ ``use=`` line within the section's configuration. If instead of a simple
+ application, you're using a WSGI :term:`pipeline` (e.g., a
+ ``[pipeline:main]`` section), the application named on the "last" element
+ will refer to your :app:`Pyramid` application. If instead of a simple
+ application or a pipeline, you're using a "composite" (e.g.,
+ ``[composite:main]``), refer to the documentation for that particular
+ composite to understand how to make it refer to your :app:`Pyramid`
+ application. In most cases, a Pyramid application built from a scaffold
+ will have a single ``[app:main]`` section in it, and this will be the
+ application served.
+
+#. The framework finds all :mod:`logging` related configuration in the ``.ini``
+ file and uses it to configure the Python standard library logging system for
+ this application. See :ref:`logging_config` for more information.
+
+#. The application's *constructor* named by the entry point referenced on the
+ ``use=`` line of the section representing your :app:`Pyramid` application is
+ passed the key/value parameters mentioned within the section in which it's
+ defined. The constructor is meant to return a :term:`router` instance,
+ which is a :term:`WSGI` application.
For :app:`Pyramid` applications, the constructor will be a function named
``main`` in the ``__init__.py`` file within the :term:`package` in which
@@ -78,14 +75,13 @@ Here's a high-level time-ordered overview of what happens when you press
Note that the constructor function accepts a ``global_config`` argument,
which is a dictionary of key/value pairs mentioned in the ``[DEFAULT]``
- section of an ``.ini`` file
- (if :ref:`[DEFAULT] <defaults_section_of_pastedeploy_file>` is present).
- It also accepts a ``**settings`` argument, which collects
- another set of arbitrary key/value pairs. The arbitrary key/value pairs
- received by this function in ``**settings`` will be composed of all the
- key/value pairs that are present in the ``[app:main]`` section (except for
- the ``use=`` setting) when this function is called by when you run
- ``pserve``.
+ section of an ``.ini`` file (if :ref:`[DEFAULT]
+ <defaults_section_of_pastedeploy_file>` is present). It also accepts a
+ ``**settings`` argument, which collects another set of arbitrary key/value
+ pairs. The arbitrary key/value pairs received by this function in
+ ``**settings`` will be composed of all the key/value pairs that are present
+ in the ``[app:main]`` section (except for the ``use=`` setting) when this
+ function is called when you run ``pserve``.
Our generated ``development.ini`` file looks like so:
@@ -95,8 +91,8 @@ Here's a high-level time-ordered overview of what happens when you press
In this case, the ``myproject.__init__:main`` function referred to by the
entry point URI ``egg:MyProject`` (see :ref:`MyProject_ini` for more
- information about entry point URIs, and how they relate to callables),
- will receive the key/value pairs ``{'pyramid.reload_templates':'true',
+ information about entry point URIs, and how they relate to callables) will
+ receive the key/value pairs ``{'pyramid.reload_templates':'true',
'pyramid.debug_authorization':'false', 'pyramid.debug_notfound':'false',
'pyramid.debug_routematch':'false', 'pyramid.debug_templates':'true',
'pyramid.default_locale_name':'en'}``. See :ref:`environment_chapter` for
@@ -114,13 +110,13 @@ Here's a high-level time-ordered overview of what happens when you press
#. The ``main`` function then calls various methods on the instance of the
class :class:`~pyramid.config.Configurator` created in the previous step.
- The intent of calling these methods is to populate an
- :term:`application registry`, which represents the :app:`Pyramid`
- configuration related to the application.
+ The intent of calling these methods is to populate an :term:`application
+ registry`, which represents the :app:`Pyramid` configuration related to the
+ application.
-#. The :meth:`~pyramid.config.Configurator.make_wsgi_app` method is called.
- The result is a :term:`router` instance. The router is associated with
- the :term:`application registry` implied by the configurator previously
+#. The :meth:`~pyramid.config.Configurator.make_wsgi_app` method is called. The
+ result is a :term:`router` instance. The router is associated with the
+ :term:`application registry` implied by the configurator previously
populated by other methods run against the Configurator. The router is a
WSGI application.
@@ -141,11 +137,10 @@ Here's a high-level time-ordered overview of what happens when you press
to receive requests.
.. seealso::
- Logging configuration is described in the :ref:`logging_chapter`
- chapter. There, in :ref:`request_logging_with_pastes_translogger`,
- you will also find an example of how to configure
- :term:`middleware` to add pre-packaged functionality to your
- application.
+ Logging configuration is described in the :ref:`logging_chapter` chapter.
+ There, in :ref:`request_logging_with_pastes_translogger`, you will also find
+ an example of how to configure :term:`middleware` to add pre-packaged
+ functionality to your application.
.. index::
pair: settings; deployment
@@ -158,8 +153,7 @@ Deployment Settings
Note that an augmented version of the values passed as ``**settings`` to the
:class:`~pyramid.config.Configurator` constructor will be available in
-:app:`Pyramid` :term:`view callable` code as ``request.registry.settings``.
-You can create objects you wish to access later from view code, and put them
-into the dictionary you pass to the configurator as ``settings``. They will
-then be present in the ``request.registry.settings`` dictionary at
-application runtime.
+:app:`Pyramid` :term:`view callable` code as ``request.registry.settings``. You
+can create objects you wish to access later from view code, and put them into
+the dictionary you pass to the configurator as ``settings``. They will then be
+present in the ``request.registry.settings`` dictionary at application runtime.
diff --git a/docs/narr/templates.rst b/docs/narr/templates.rst
index 4c1364493..9e3a31845 100644
--- a/docs/narr/templates.rst
+++ b/docs/narr/templates.rst
@@ -3,15 +3,14 @@
Templates
=========
-A :term:`template` is a file on disk which can be used to render
-dynamic data provided by a :term:`view`. :app:`Pyramid` offers a
-number of ways to perform templating tasks out of the box, and
-provides add-on templating support through a set of bindings packages.
+A :term:`template` is a file on disk which can be used to render dynamic data
+provided by a :term:`view`. :app:`Pyramid` offers a number of ways to perform
+templating tasks out of the box, and provides add-on templating support through
+a set of bindings packages.
-Before discussing how built-in templates are used in
-detail, we'll discuss two ways to render templates within
-:app:`Pyramid` in general: directly, and via renderer
-configuration.
+Before discussing how built-in templates are used in detail, we'll discuss two
+ways to render templates within :app:`Pyramid` in general: directly and via
+renderer configuration.
.. index::
single: templates used directly
@@ -21,16 +20,15 @@ configuration.
Using Templates Directly
------------------------
-The most straightforward way to use a template within
-:app:`Pyramid` is to cause it to be rendered directly within a
-:term:`view callable`. You may use whatever API is supplied by a
-given templating engine to do so.
+The most straightforward way to use a template within :app:`Pyramid` is to
+cause it to be rendered directly within a :term:`view callable`. You may use
+whatever API is supplied by a given templating engine to do so.
-:app:`Pyramid` provides various APIs that allow you to render templates
-directly from within a view callable. For example, if there is a
-:term:`Chameleon` ZPT template named ``foo.pt`` in a directory named
-``templates`` in your application, you can render the template from
-within the body of a view callable like so:
+:app:`Pyramid` provides various APIs that allow you to render templates directly
+from within a view callable. For example, if there is a :term:`Chameleon` ZPT
+template named ``foo.pt`` in a directory named ``templates`` in your
+application, you can render the template from within the body of a view
+callable like so:
.. code-block:: python
:linenos:
@@ -43,23 +41,21 @@ within the body of a view callable like so:
request=request)
The ``sample_view`` :term:`view callable` function above returns a
-:term:`response` object which contains the body of the
-``templates/foo.pt`` template. In this case, the ``templates``
-directory should live in the same directory as the module containing
-the ``sample_view`` function. The template author will have the names
-``foo`` and ``bar`` available as top-level names for replacement or
-comparison purposes.
+:term:`response` object which contains the body of the ``templates/foo.pt``
+template. In this case, the ``templates`` directory should live in the same
+directory as the module containing the ``sample_view`` function. The template
+author will have the names ``foo`` and ``bar`` available as top-level names for
+replacement or comparison purposes.
In the example above, the path ``templates/foo.pt`` is relative to the
-directory containing the file which defines the view configuration.
-In this case, this is the directory containing the file that
-defines the ``sample_view`` function. Although a renderer path is
-usually just a simple relative pathname, a path named as a renderer
-can be absolute, starting with a slash on UNIX or a drive letter
-prefix on Windows. The path can alternately be an
-:term:`asset specification` in the form
-``some.dotted.package_name:relative/path``. This makes it possible to
-address template assets which live in another package. For example:
+directory containing the file which defines the view configuration. In this
+case, this is the directory containing the file that defines the
+``sample_view`` function. Although a renderer path is usually just a simple
+relative pathname, a path named as a renderer can be absolute, starting with a
+slash on UNIX or a drive letter prefix on Windows. The path can alternatively
+be an :term:`asset specification` in the form
+``some.dotted.package_name:relative/path``. This makes it possible to address
+template assets which live in another package. For example:
.. code-block:: python
:linenos:
@@ -71,38 +67,36 @@ address template assets which live in another package. For example:
{'foo':1, 'bar':2},
request=request)
-An asset specification points at a file within a Python *package*.
-In this case, it points at a file named ``foo.pt`` within the
-``templates`` directory of the ``mypackage`` package. Using an
-asset specification instead of a relative template name is usually
-a good idea, because calls to :func:`~pyramid.renderers.render_to_response`
-using asset specifications will continue to work properly if you move the
-code containing them to another location.
+An asset specification points at a file within a Python *package*. In this
+case, it points at a file named ``foo.pt`` within the ``templates`` directory
+of the ``mypackage`` package. Using an asset specification instead of a
+relative template name is usually a good idea, because calls to
+:func:`~pyramid.renderers.render_to_response` using asset specifications will
+continue to work properly if you move the code containing them to another
+location.
In the examples above we pass in a keyword argument named ``request``
-representing the current :app:`Pyramid` request. Passing a request
-keyword argument will cause the ``render_to_response`` function to
-supply the renderer with more correct system values (see
-:ref:`renderer_system_values`), because most of the information required
-to compose proper system values is present in the request. If your
-template relies on the name ``request`` or ``context``, or if you've
-configured special :term:`renderer globals`, make sure to pass
+representing the current :app:`Pyramid` request. Passing a request keyword
+argument will cause the ``render_to_response`` function to supply the renderer
+with more correct system values (see :ref:`renderer_system_values`), because
+most of the information required to compose proper system values is present in
+the request. If your template relies on the name ``request`` or ``context``,
+or if you've configured special :term:`renderer globals`, make sure to pass
``request`` as a keyword argument in every call to a
``pyramid.renderers.render_*`` function.
-Every view must return a :term:`response` object, except for views
-which use a :term:`renderer` named via view configuration (which we'll
-see shortly). The :func:`pyramid.renderers.render_to_response`
-function is a shortcut function that actually returns a response
-object. This allows the example view above to simply return the result
-of its call to ``render_to_response()`` directly.
+Every view must return a :term:`response` object, except for views which use a
+:term:`renderer` named via view configuration (which we'll see shortly). The
+:func:`pyramid.renderers.render_to_response` function is a shortcut function
+that actually returns a response object. This allows the example view above to
+simply return the result of its call to ``render_to_response()`` directly.
Obviously not all APIs you might call to get response data will return a
-response object. For example, you might render one or more templates to
-a string that you want to use as response data. The
-:func:`pyramid.renderers.render` API renders a template to a string. We
-can manufacture a :term:`response` object directly, and use that string
-as the body of the response:
+response object. For example, you might render one or more templates to a
+string that you want to use as response data. The
+:func:`pyramid.renderers.render` API renders a template to a string. We can
+manufacture a :term:`response` object directly, and use that string as the body
+of the response:
.. code-block:: python
:linenos:
@@ -119,10 +113,10 @@ as the body of the response:
Because :term:`view callable` functions are typically the only code in
:app:`Pyramid` that need to know anything about templates, and because view
-functions are very simple Python, you can use whatever templating system you're
-most comfortable with within :app:`Pyramid`. Install the templating system,
-import its API functions into your views module, use those APIs to generate a
-string, then return that string as the body of a :app:`Pyramid`
+functions are very simple Python, you can use whatever templating system with
+which you're most comfortable within :app:`Pyramid`. Install the templating
+system, import its API functions into your views module, use those APIs to
+generate a string, then return that string as the body of a :app:`Pyramid`
:term:`Response` object.
For example, here's an example of using "raw" Mako_ from within a
@@ -141,34 +135,32 @@ For example, here's an example of using "raw" Mako_ from within a
return response
You probably wouldn't use this particular snippet in a project, because it's
-easier to use the supported
-:ref:`Mako bindings <available_template_system_bindings>`. But if your
-favorite templating system is not supported as a renderer extension for
-:app:`Pyramid`, you can create your own simple combination as shown above.
+easier to use the supported :ref:`Mako bindings
+<available_template_system_bindings>`. But if your favorite templating system
+is not supported as a renderer extension for :app:`Pyramid`, you can create
+your own simple combination as shown above.
.. note::
If you use third-party templating languages without cooperating
:app:`Pyramid` bindings directly within view callables, the
- auto-template-reload strategy explained in
- :ref:`reload_templates_section` will not be available, nor will the
- template asset overriding capability explained in
- :ref:`overriding_assets_section` be available, nor will it be
- possible to use any template using that language as a
- :term:`renderer`. However, it's reasonably easy to write custom
- templating system binding packages for use under :app:`Pyramid` so
- that templates written in the language can be used as renderers.
- See :ref:`adding_and_overriding_renderers` for instructions on how
- to create your own template renderer and
- :ref:`available_template_system_bindings` for example packages.
-
-If you need more control over the status code and content-type, or
-other response attributes from views that use direct templating, you
-may set attributes on the response that influence these values.
-
-Here's an example of changing the content-type and status of the
-response object returned by
-:func:`~pyramid.renderers.render_to_response`:
+ auto-template-reload strategy explained in :ref:`reload_templates_section`
+ will not be available, nor will the template asset overriding capability
+ explained in :ref:`overriding_assets_section` be available, nor will it be
+ possible to use any template using that language as a :term:`renderer`.
+ However, it's reasonably easy to write custom templating system binding
+ packages for use under :app:`Pyramid` so that templates written in the
+ language can be used as renderers. See
+ :ref:`adding_and_overriding_renderers` for instructions on how to create
+ your own template renderer and :ref:`available_template_system_bindings`
+ for example packages.
+
+If you need more control over the status code and content-type, or other
+response attributes from views that use direct templating, you may set
+attributes on the response that influence these values.
+
+Here's an example of changing the content-type and status of the response
+object returned by :func:`~pyramid.renderers.render_to_response`:
.. code-block:: python
:linenos:
@@ -183,8 +175,8 @@ response object returned by
response.status_int = 204
return response
-Here's an example of manufacturing a response object using the result
-of :func:`~pyramid.renderers.render` (a string):
+Here's an example of manufacturing a response object using the result of
+:func:`~pyramid.renderers.render` (a string):
.. code-block:: python
:linenos:
@@ -214,9 +206,8 @@ of :func:`~pyramid.renderers.render` (a string):
System Values Used During Rendering
-----------------------------------
-When a template is rendered using
-:func:`~pyramid.renderers.render_to_response` or
-:func:`~pyramid.renderers.render`, or a ``renderer=`` argument to view
+When a template is rendered using :func:`~pyramid.renderers.render_to_response`
+or :func:`~pyramid.renderers.render`, or a ``renderer=`` argument to view
configuration (see :ref:`templates_used_as_renderers`), the renderer
representing the template will be provided with a number of *system* values.
These values are provided to the template:
@@ -232,31 +223,31 @@ These values are provided to the template:
``context``
The current :app:`Pyramid` :term:`context` if ``request`` was provided as a
- keyword argument to ``render_to_response`` or ``render``, or ``None`` if
- the ``request`` keyword argument was not provided. This value will always
- be provided if the template is rendered as the result of a ``renderer=``
- argument to view configuration being used.
+ keyword argument to ``render_to_response`` or ``render``, or ``None`` if the
+ ``request`` keyword argument was not provided. This value will always be
+ provided if the template is rendered as the result of a ``renderer=``
+ argument to the view configuration being used.
``renderer_name``
- The renderer name used to perform the rendering,
- e.g. ``mypackage:templates/foo.pt``.
+ The renderer name used to perform the rendering, e.g.,
+ ``mypackage:templates/foo.pt``.
``renderer_info``
An object implementing the :class:`pyramid.interfaces.IRendererInfo`
interface. Basically, an object with the following attributes: ``name``,
- ``package`` and ``type``.
+ ``package``, and ``type``.
``view``
- The view callable object that was used to render this template. If the
- view callable is a method of a class-based view, this will be an instance
- of the class that the method was defined on. If the view callable is a
- function or instance, it will be that function or instance. Note that this
- value will only be automatically present when a template is rendered as a
- result of a ``renderer=`` argument; it will be ``None`` when the
- ``render_to_response`` or ``render`` APIs are used.
+ The view callable object that was used to render this template. If the view
+ callable is a method of a class-based view, this will be an instance of the
+ class that the method was defined on. If the view callable is a function or
+ instance, it will be that function or instance. Note that this value will
+ only be automatically present when a template is rendered as a result of a
+ ``renderer=`` argument; it will be ``None`` when the ``render_to_response``
+ or ``render`` APIs are used.
-You can define more values which will be passed to every template executed as
-a result of rendering by defining :term:`renderer globals`.
+You can define more values which will be passed to every template executed as a
+result of rendering by defining :term:`renderer globals`.
What any particular renderer does with these system values is up to the
renderer itself, but most template renderers make these names available as
@@ -270,26 +261,23 @@ top-level template variables.
Templates Used as Renderers via Configuration
---------------------------------------------
-An alternative to using :func:`~pyramid.renderers.render_to_response`
-to render templates manually in your view callable code, is
-to specify the template as a :term:`renderer` in your
-*view configuration*. This can be done with any of the
+An alternative to using :func:`~pyramid.renderers.render_to_response` to render
+templates manually in your view callable code is to specify the template as a
+:term:`renderer` in your *view configuration*. This can be done with any of the
templating languages supported by :app:`Pyramid`.
-To use a renderer via view configuration, specify a template
-:term:`asset specification` as the ``renderer`` argument, or
-attribute to the :term:`view configuration` of a :term:`view
-callable`. Then return a *dictionary* from that view callable. The
-dictionary items returned by the view callable will be made available
-to the renderer template as top-level names.
+To use a renderer via view configuration, specify a template :term:`asset
+specification` as the ``renderer`` argument, or attribute to the :term:`view
+configuration` of a :term:`view callable`. Then return a *dictionary* from
+that view callable. The dictionary items returned by the view callable will be
+made available to the renderer template as top-level names.
-The association of a template as a renderer for a :term:`view
-configuration` makes it possible to replace code within a :term:`view
-callable` that handles the rendering of a template.
+The association of a template as a renderer for a :term:`view configuration`
+makes it possible to replace code within a :term:`view callable` that handles
+the rendering of a template.
-Here's an example of using a :class:`~pyramid.view.view_config`
-decorator to specify a :term:`view configuration` that names a
-template renderer:
+Here's an example of using a :class:`~pyramid.view.view_config` decorator to
+specify a :term:`view configuration` that names a template renderer:
.. code-block:: python
:linenos:
@@ -302,11 +290,10 @@ template renderer:
.. note::
- You do not need to supply the ``request`` value as a key
- in the dictionary result returned from a renderer-configured view
- callable. :app:`Pyramid` automatically supplies this value for
- you so that the "most correct" system values are provided to
- the renderer.
+ You do not need to supply the ``request`` value as a key in the dictionary
+ result returned from a renderer-configured view callable. :app:`Pyramid`
+ automatically supplies this value for you, so that the "most correct" system
+ values are provided to the renderer.
.. warning::
@@ -314,7 +301,7 @@ template renderer:
shown above is the template *path*. In the example above, the path
``templates/foo.pt`` is *relative*. Relative to what, you ask? Because
we're using a Chameleon renderer, it means "relative to the directory in
- which the file which defines the view configuration lives". In this case,
+ which the file that defines the view configuration lives". In this case,
this is the directory containing the file that defines the ``my_view``
function.
@@ -327,7 +314,7 @@ Similar renderer configuration can be done imperatively. See
Although a renderer path is usually just a simple relative pathname, a path
named as a renderer can be absolute, starting with a slash on UNIX or a drive
-letter prefix on Windows. The path can alternately be an :term:`asset
+letter prefix on Windows. The path can alternatively be an :term:`asset
specification` in the form ``some.dotted.package_name:relative/path``, making
it possible to address template assets which live in another package.
@@ -335,32 +322,31 @@ Not just any template from any arbitrary templating system may be used as a
renderer. Bindings must exist specifically for :app:`Pyramid` to use a
templating language template as a renderer.
-.. sidebar:: Why Use A Renderer via View Configuration
-
- Using a renderer in view configuration is usually a better way to
- render templates than using any rendering API directly from within a
- :term:`view callable` because it makes the view callable more
- unit-testable. Views which use templating or rendering APIs directly
- must return a :term:`Response` object. Making testing assertions
- about response objects is typically an indirect process, because it
- means that your test code often needs to somehow parse information
- out of the response body (often HTML). View callables configured
- with renderers externally via view configuration typically return a
- dictionary, as above. Making assertions about results returned in a
- dictionary is almost always more direct and straightforward than
- needing to parse HTML.
+.. sidebar:: Why Use a Renderer via View Configuration
+
+ Using a renderer in view configuration is usually a better way to render
+ templates than using any rendering API directly from within a :term:`view
+ callable` because it makes the view callable more unit-testable. Views
+ which use templating or rendering APIs directly must return a
+ :term:`Response` object. Making testing assertions about response objects
+ is typically an indirect process, because it means that your test code often
+ needs to somehow parse information out of the response body (often HTML).
+ View callables configured with renderers externally via view configuration
+ typically return a dictionary, as above. Making assertions about results
+ returned in a dictionary is almost always more direct and straightforward
+ than needing to parse HTML.
By default, views rendered via a template renderer return a :term:`Response`
object which has a *status code* of ``200 OK``, and a *content-type* of
``text/html``. To vary attributes of the response of a view that uses a
-renderer, such as the content-type, headers, or status attributes, you must
-use the API of the :class:`pyramid.response.Response` object exposed as
+renderer, such as the content-type, headers, or status attributes, you must use
+the API of the :class:`pyramid.response.Response` object exposed as
``request.response`` within the view before returning the dictionary. See
:ref:`request_response_attr` for more information.
-The same set of system values are provided to templates rendered via a
-renderer view configuration as those provided to templates rendered
-imperatively. See :ref:`renderer_system_values`.
+The same set of system values are provided to templates rendered via a renderer
+view configuration as those provided to templates rendered imperatively. See
+:ref:`renderer_system_values`.
.. index::
pair: debugging; templates
@@ -401,32 +387,31 @@ displaying the arguments passed to the template itself.
Automatically Reloading Templates
---------------------------------
-It's often convenient to see changes you make to a template file
-appear immediately without needing to restart the application process.
-:app:`Pyramid` allows you to configure your application development
-environment so that a change to a template will be automatically
-detected, and the template will be reloaded on the next rendering.
+It's often convenient to see changes you make to a template file appear
+immediately without needing to restart the application process. :app:`Pyramid`
+allows you to configure your application development environment so that a
+change to a template will be automatically detected, and the template will be
+reloaded on the next rendering.
.. warning::
- Auto-template-reload behavior is not recommended for
- production sites as it slows rendering slightly; it's
- usually only desirable during development.
+ Auto-template-reload behavior is not recommended for production sites as it
+ slows rendering slightly; it's usually only desirable during development.
In order to turn on automatic reloading of templates, you can use an
-environment variable, or a configuration file setting.
+environment variable or a configuration file setting.
-To use an environment variable, start your application under a shell
-using the ``PYRAMID_RELOAD_TEMPLATES`` operating system environment
-variable set to ``1``, For example:
+To use an environment variable, start your application under a shell using the
+``PYRAMID_RELOAD_TEMPLATES`` operating system environment variable set to
+``1``, For example:
.. code-block:: text
$ PYRAMID_RELOAD_TEMPLATES=1 $VENV/bin/pserve myproject.ini
-To use a setting in the application ``.ini`` file for the same
-purpose, set the ``pyramid.reload_templates`` key to ``true`` within the
-application's configuration section, e.g.:
+To use a setting in the application ``.ini`` file for the same purpose, set the
+``pyramid.reload_templates`` key to ``true`` within the application's
+configuration section, e.g.:
.. code-block:: ini
:linenos:
diff --git a/docs/narr/urldispatch.rst b/docs/narr/urldispatch.rst
index fa3e734fe..c13558008 100644
--- a/docs/narr/urldispatch.rst
+++ b/docs/narr/urldispatch.rst
@@ -8,7 +8,7 @@ URL Dispatch
:term:`URL dispatch` provides a simple way to map URLs to :term:`view` code
using a simple pattern matching language. An ordered set of patterns is
-checked one-by-one. If one of the patterns matches the path information
+checked one by one. If one of the patterns matches the path information
associated with a request, a particular :term:`view callable` is invoked. A
view callable is a specific bit of code, defined in your application, that
receives the :term:`request` and returns a :term:`response` object.
@@ -21,12 +21,12 @@ If any route configuration is present in an application, the :app:`Pyramid`
matching patterns present in a *route map*.
If any route pattern matches the information in the :term:`request`,
-:app:`Pyramid` will invoke the :term:`view lookup` process to find a
-matching view.
+:app:`Pyramid` will invoke the :term:`view lookup` process to find a matching
+view.
If no route pattern in the route map matches the information in the
-:term:`request` provided in your application, :app:`Pyramid` will fail over
-to using :term:`traversal` to perform resource location and view lookup.
+:term:`request` provided in your application, :app:`Pyramid` will fail over to
+using :term:`traversal` to perform resource location and view lookup.
.. index::
single: route configuration
@@ -35,11 +35,11 @@ Route Configuration
-------------------
:term:`Route configuration` is the act of adding a new :term:`route` to an
-application. A route has a *name*, which acts as an identifier to be used
-for URL generation. The name also allows developers to associate a view
+application. A route has a *name*, which acts as an identifier to be used for
+URL generation. The name also allows developers to associate a view
configuration with the route. A route also has a *pattern*, meant to match
against the ``PATH_INFO`` portion of a URL (the portion following the scheme
-and port, e.g. ``/foo/bar`` in the URL `<http://localhost:8080/foo/bar>`_). It
+and port, e.g., ``/foo/bar`` in the URL ``http://localhost:8080/foo/bar``). It
also optionally has a ``factory`` and a set of :term:`route predicate`
attributes.
@@ -71,8 +71,8 @@ invoked when the associated route pattern matches during a request.
More commonly, you will not use any ``add_view`` statements in your project's
"setup" code. You will instead use ``add_route`` statements, and use a
-:term:`scan` to associate view callables with routes. For example, if
-this is a portion of your project's ``__init__.py``:
+:term:`scan` to associate view callables with routes. For example, if this is
+a portion of your project's ``__init__.py``:
.. code-block:: python
@@ -85,8 +85,8 @@ setup code. However, the above :term:`scan` execution
decoration`, including any objects decorated with the
:class:`pyramid.view.view_config` decorator in the ``mypackage`` Python
package. For example, if you have a ``views.py`` in your package, a scan will
-pick up any of its configuration decorators, so we can add one there
-that references ``myroute`` as a ``route_name`` parameter:
+pick up any of its configuration decorators, so we can add one there that
+references ``myroute`` as a ``route_name`` parameter:
.. code-block:: python
@@ -97,8 +97,8 @@ that references ``myroute`` as a ``route_name`` parameter:
def myview(request):
return Response('OK')
-The above combination of ``add_route`` and ``scan`` is completely equivalent
-to using the previous combination of ``add_route`` and ``add_view``.
+The above combination of ``add_route`` and ``scan`` is completely equivalent to
+using the previous combination of ``add_route`` and ``add_view``.
.. index::
single: route path pattern syntax
@@ -109,13 +109,13 @@ to using the previous combination of ``add_route`` and ``add_view``.
Route Pattern Syntax
~~~~~~~~~~~~~~~~~~~~
-The syntax of the pattern matching language used by :app:`Pyramid` URL
-dispatch in the *pattern* argument is straightforward; it is close to that of
-the :term:`Routes` system used by :term:`Pylons`.
+The syntax of the pattern matching language used by :app:`Pyramid` URL dispatch
+in the *pattern* argument is straightforward. It is close to that of the
+:term:`Routes` system used by :term:`Pylons`.
-The *pattern* used in route configuration may start with a slash character.
-If the pattern does not start with a slash character, an implicit slash will
-be prepended to it at matching time. For example, the following patterns are
+The *pattern* used in route configuration may start with a slash character. If
+the pattern does not start with a slash character, an implicit slash will be
+prepended to it at matching time. For example, the following patterns are
equivalent:
.. code-block:: text
@@ -128,28 +128,29 @@ and:
/{foo}/bar/baz
-If a pattern is a valid URL it won't be ever matched against an incoming
-request. Instead it can be useful for generating external URLs. See
-:ref:`External routes <external_route_narr>` for details.
+If a pattern is a valid URL it won't be matched against an incoming request.
+Instead it can be useful for generating external URLs. See :ref:`External
+routes <external_route_narr>` for details.
-A pattern segment (an individual item between ``/`` characters in the
-pattern) may either be a literal string (e.g. ``foo``) *or* it may be a
-replacement marker (e.g. ``{foo}``) or a certain combination of both. A
-replacement marker does not need to be preceded by a ``/`` character.
+A pattern segment (an individual item between ``/`` characters in the pattern)
+may either be a literal string (e.g., ``foo``) *or* it may be a replacement
+marker (e.g., ``{foo}``), or a certain combination of both. A replacement
+marker does not need to be preceded by a ``/`` character.
-A replacement marker is in the format ``{name}``, where this means "accept
-any characters up to the next slash character and use this as the ``name``
+A replacement marker is in the format ``{name}``, where this means "accept any
+characters up to the next slash character and use this as the ``name``
:term:`matchdict` value."
A replacement marker in a pattern must begin with an uppercase or lowercase
ASCII letter or an underscore, and can be composed only of uppercase or
lowercase ASCII letters, underscores, and numbers. For example: ``a``,
-``a_b``, ``_b``, and ``b9`` are all valid replacement marker names, but
-``0a`` is not.
+``a_b``, ``_b``, and ``b9`` are all valid replacement marker names, but ``0a``
+is not.
-.. note:: A replacement marker could not start with an underscore until
- Pyramid 1.2. Previous versions required that the replacement marker start
- with an uppercase or lowercase letter.
+.. versionchanged:: 1.2
+ A replacement marker could not start with an underscore until Pyramid 1.2.
+ Previous versions required that the replacement marker start with an
+ uppercase or lowercase letter.
A matchdict is the dictionary representing the dynamic parts extracted from a
URL based on the routing pattern. It is available as ``request.matchdict``.
@@ -174,18 +175,18 @@ It will not match the following patterns however:
foo/1/2/ -> No match (trailing slash)
bar/abc/def -> First segment literal mismatch
-The match for a segment replacement marker in a segment will be done only up
-to the first non-alphanumeric character in the segment in the pattern. So,
-for instance, if this route pattern was used:
+The match for a segment replacement marker in a segment will be done only up to
+the first non-alphanumeric character in the segment in the pattern. So, for
+instance, if this route pattern was used:
.. code-block:: text
foo/{name}.html
-The literal path ``/foo/biz.html`` will match the above route pattern, and
-the match result will be ``{'name':u'biz'}``. However, the literal path
-``/foo/biz`` will not match, because it does not contain a literal ``.html``
-at the end of the segment represented by ``{name}.html`` (it only contains
+The literal path ``/foo/biz.html`` will match the above route pattern, and the
+match result will be ``{'name':u'biz'}``. However, the literal path
+``/foo/biz`` will not match, because it does not contain a literal ``.html`` at
+the end of the segment represented by ``{name}.html`` (it only contains
``biz``, not ``biz.html``).
To capture both segments, two replacement markers can be used:
@@ -194,28 +195,27 @@ To capture both segments, two replacement markers can be used:
foo/{name}.{ext}
-The literal path ``/foo/biz.html`` will match the above route pattern, and
-the match result will be ``{'name': 'biz', 'ext': 'html'}``. This occurs
-because there is a literal part of ``.`` (period) between the two replacement
-markers ``{name}`` and ``{ext}``.
+The literal path ``/foo/biz.html`` will match the above route pattern, and the
+match result will be ``{'name': 'biz', 'ext': 'html'}``. This occurs because
+there is a literal part of ``.`` (period) between the two replacement markers
+``{name}`` and ``{ext}``.
Replacement markers can optionally specify a regular expression which will be
-used to decide whether a path segment should match the marker. To specify
-that a replacement marker should match only a specific set of characters as
-defined by a regular expression, you must use a slightly extended form of
-replacement marker syntax. Within braces, the replacement marker name must
-be followed by a colon, then directly thereafter, the regular expression.
-The *default* regular expression associated with a replacement marker
-``[^/]+`` matches one or more characters which are not a slash. For example,
-under the hood, the replacement marker ``{foo}`` can more verbosely be
-spelled as ``{foo:[^/]+}``. You can change this to be an arbitrary regular
-expression to match an arbitrary sequence of characters, such as
-``{foo:\d+}`` to match only digits.
+used to decide whether a path segment should match the marker. To specify that
+a replacement marker should match only a specific set of characters as defined
+by a regular expression, you must use a slightly extended form of replacement
+marker syntax. Within braces, the replacement marker name must be followed by
+a colon, then directly thereafter, the regular expression. The *default*
+regular expression associated with a replacement marker ``[^/]+`` matches one
+or more characters which are not a slash. For example, under the hood, the
+replacement marker ``{foo}`` can more verbosely be spelled as ``{foo:[^/]+}``.
+You can change this to be an arbitrary regular expression to match an arbitrary
+sequence of characters, such as ``{foo:\d+}`` to match only digits.
It is possible to use two replacement markers without any literal characters
between them, for instance ``/{foo}{bar}``. However, this would be a
-nonsensical pattern without specifying a custom regular expression to
-restrict what each marker captures.
+nonsensical pattern without specifying a custom regular expression to restrict
+what each marker captures.
Segments must contain at least one character in order to match a segment
replacement marker. For example, for the URL ``/abc/``:
@@ -224,7 +224,7 @@ replacement marker. For example, for the URL ``/abc/``:
- ``/{foo}/`` will match.
-Note that values representing matched path segments will be url-unquoted and
+Note that values representing matched path segments will be URL-unquoted and
decoded from UTF-8 into Unicode within the matchdict. So for instance, the
following pattern:
@@ -244,9 +244,9 @@ The matchdict will look like so (the value is URL-decoded / UTF-8 decoded):
{'bar':u'La Pe\xf1a'}
-Literal strings in the path segment should represent the *decoded* value of
-the ``PATH_INFO`` provided to Pyramid. You don't want to use a URL-encoded
-value or a bytestring representing the literal's UTF-8 in the pattern. For
+Literal strings in the path segment should represent the *decoded* value of the
+``PATH_INFO`` provided to Pyramid. You don't want to use a URL-encoded value
+or a bytestring representing the literal encoded as UTF-8 in the pattern. For
example, rather than this:
.. code-block:: text
@@ -259,8 +259,8 @@ You'll want to use something like this:
/Foo Bar/{baz}
-For patterns that contain "high-order" characters in its literals, you'll
-want to use a Unicode value as the pattern as opposed to any URL-encoded or
+For patterns that contain "high-order" characters in its literals, you'll want
+to use a Unicode value as the pattern as opposed to any URL-encoded or
UTF-8-encoded value. For example, you might be tempted to use a bytestring
pattern like this:
@@ -268,12 +268,11 @@ pattern like this:
/La Pe\xc3\xb1a/{x}
-But this will either cause an error at startup time or it won't match
-properly. You'll want to use a Unicode value as the pattern instead rather
-than raw bytestring escapes. You can use a high-order Unicode value as the
-pattern by using `Python source file encoding
-<http://www.python.org/dev/peps/pep-0263/>`_ plus the "real" character in the
-Unicode pattern in the source, like so:
+But this will either cause an error at startup time or it won't match properly.
+You'll want to use a Unicode value as the pattern instead rather than raw
+bytestring escapes. You can use a high-order Unicode value as the pattern by
+using `Python source file encoding <http://www.python.org/dev/peps/pep-0263/>`_
+plus the "real" character in the Unicode pattern in the source, like so:
.. code-block:: text
@@ -291,8 +290,8 @@ only to literals in the pattern.
If the pattern has a ``*`` in it, the name which follows it is considered a
"remainder match". A remainder match *must* come at the end of the pattern.
-Unlike segment replacement markers, it does not need to be preceded by a
-slash. For example:
+Unlike segment replacement markers, it does not need to be preceded by a slash.
+For example:
.. code-block:: text
@@ -310,7 +309,7 @@ The above pattern will match these URLs, generating the following matchdicts:
Note that when a ``*stararg`` remainder match is matched, the value put into
the matchdict is turned into a tuple of path segments representing the
-remainder of the path. These path segments are url-unquoted and decoded from
+remainder of the path. These path segments are URL-unquoted and decoded from
UTF-8 into Unicode. For example, for the following pattern:
.. code-block:: text
@@ -357,15 +356,15 @@ Route Declaration Ordering
Route configuration declarations are evaluated in a specific order when a
request enters the system. As a result, the order of route configuration
-declarations is very important. The order that routes declarations are
+declarations is very important. The order in which route declarations are
evaluated is the order in which they are added to the application at startup
time. (This is unlike a different way of mapping URLs to code that
:app:`Pyramid` provides, named :term:`traversal`, which does not depend on
pattern ordering).
For routes added via the :mod:`~pyramid.config.Configurator.add_route` method,
-the order that routes are evaluated is the order in which they are added to
-the configuration imperatively.
+the order that routes are evaluated is the order in which they are added to the
+configuration imperatively.
For example, route configuration statements with the following patterns might
be added in the following order:
@@ -375,10 +374,9 @@ be added in the following order:
members/{def}
members/abc
-In such a configuration, the ``members/abc`` pattern would *never* be
-matched. This is because the match ordering will always match
-``members/{def}`` first; the route configuration with ``members/abc`` will
-never be evaluated.
+In such a configuration, the ``members/abc`` pattern would *never* be matched.
+This is because the match ordering will always match ``members/{def}`` first;
+the route configuration with ``members/abc`` will never be evaluated.
.. index::
single: route configuration arguments
@@ -416,19 +414,18 @@ the system, for each route configuration declaration present in the system,
declared. This checking happens in the order that the routes were declared
via :meth:`pyramid.config.Configurator.add_route`.
-When a route configuration is declared, it may contain :term:`route
-predicate` arguments. All route predicates associated with a route
-declaration must be ``True`` for the route configuration to be used for a
-given request during a check. If any predicate in the set of :term:`route
-predicate` arguments provided to a route configuration returns ``False``
-during a check, that route is skipped and route matching continues through
-the ordered set of routes.
+When a route configuration is declared, it may contain :term:`route predicate`
+arguments. All route predicates associated with a route declaration must be
+``True`` for the route configuration to be used for a given request during a
+check. If any predicate in the set of :term:`route predicate` arguments
+provided to a route configuration returns ``False`` during a check, that route
+is skipped and route matching continues through the ordered set of routes.
If any route matches, the route matching process stops and the :term:`view
-lookup` subsystem takes over to find the most reasonable view callable for
-the matched route. Most often, there's only one view that will match (a view
-configured with a ``route_name`` argument matching the matched route). To
-gain a better understanding of how routes and views are associated in a real
+lookup` subsystem takes over to find the most reasonable view callable for the
+matched route. Most often, there's only one view that will match (a view
+configured with a ``route_name`` argument matching the matched route). To gain
+a better understanding of how routes and views are associated in a real
application, you can use the ``pviews`` command, as documented in
:ref:`displaying_matching_views`.
@@ -445,11 +442,10 @@ The Matchdict
~~~~~~~~~~~~~
When the URL pattern associated with a particular route configuration is
-matched by a request, a dictionary named ``matchdict`` is added as an
-attribute of the :term:`request` object. Thus, ``request.matchdict`` will
-contain the values that match replacement patterns in the ``pattern``
-element. The keys in a matchdict will be strings. The values will be
-Unicode objects.
+matched by a request, a dictionary named ``matchdict`` is added as an attribute
+of the :term:`request` object. Thus, ``request.matchdict`` will contain the
+values that match replacement patterns in the ``pattern`` element. The keys in
+a matchdict will be strings. The values will be Unicode objects.
.. note::
@@ -466,10 +462,10 @@ The Matched Route
When the URL pattern associated with a particular route configuration is
matched by a request, an object named ``matched_route`` is added as an
-attribute of the :term:`request` object. Thus, ``request.matched_route``
-will be an object implementing the :class:`~pyramid.interfaces.IRoute`
-interface which matched the request. The most useful attribute of the route
-object is ``name``, which is the name of the route that matched.
+attribute of the :term:`request` object. Thus, ``request.matched_route`` will
+be an object implementing the :class:`~pyramid.interfaces.IRoute` interface
+which matched the request. The most useful attribute of the route object is
+``name``, which is the name of the route that matched.
.. note::
@@ -480,8 +476,8 @@ Routing Examples
----------------
Let's check out some examples of how route configuration statements might be
-commonly declared, and what will happen if they are matched by the
-information present in a request.
+commonly declared, and what will happen if they are matched by the information
+present in a request.
.. _urldispatch_example1:
@@ -505,18 +501,18 @@ configuration will be invoked.
Recall that the ``@view_config`` is equivalent to calling ``config.add_view``,
because the ``config.scan()`` call will import ``mypackage.views``, shown
below, and execute ``config.add_view`` under the hood. Each view then maps the
-route name to the matching view callable. In the case of the above
-example, when the URL of a request matches ``/site/{id}``, the view callable at
-the Python dotted path name ``mypackage.views.site_view`` will be called with
-the request. In other words, we've associated a view callable directly with a
+route name to the matching view callable. In the case of the above example,
+when the URL of a request matches ``/site/{id}``, the view callable at the
+Python dotted path name ``mypackage.views.site_view`` will be called with the
+request. In other words, we've associated a view callable directly with a
route pattern.
When the ``/site/{id}`` route pattern matches during a request, the
-``site_view`` view callable is invoked with that request as its sole
-argument. When this route matches, a ``matchdict`` will be generated and
-attached to the request as ``request.matchdict``. If the specific URL
-matched is ``/site/1``, the ``matchdict`` will be a dictionary with a single
-key, ``id``; the value will be the string ``'1'``, ex.: ``{'id':'1'}``.
+``site_view`` view callable is invoked with that request as its sole argument.
+When this route matches, a ``matchdict`` will be generated and attached to the
+request as ``request.matchdict``. If the specific URL matched is ``/site/1``,
+the ``matchdict`` will be a dictionary with a single key, ``id``; the value
+will be the string ``'1'``, ex.: ``{'id':'1'}``.
The ``mypackage.views`` module referred to above might look like so:
@@ -539,8 +535,8 @@ information about views.
Example 2
~~~~~~~~~
-Below is an example of a more complicated set of route statements you might
-add to your application:
+Below is an example of a more complicated set of route statements you might add
+to your application:
.. code-block:: python
:linenos:
@@ -587,33 +583,32 @@ forms:
and attached to the :term:`request` will consist of ``{'idea':'1'}``.
- When a URL matches the pattern ``/users/{user}``, the view callable
- available at the dotted Python pathname ``mypackage.views.user_view`` will
- be called. For the specific URL ``/users/1``, the ``matchdict`` generated
- and attached to the :term:`request` will consist of ``{'user':'1'}``.
+ available at the dotted Python pathname ``mypackage.views.user_view`` will be
+ called. For the specific URL ``/users/1``, the ``matchdict`` generated and
+ attached to the :term:`request` will consist of ``{'user':'1'}``.
- When a URL matches the pattern ``/tags/{tag}``, the view callable available
at the dotted Python pathname ``mypackage.views.tag_view`` will be called.
- For the specific URL ``/tags/1``, the ``matchdict`` generated and attached
- to the :term:`request` will consist of ``{'tag':'1'}``.
+ For the specific URL ``/tags/1``, the ``matchdict`` generated and attached to
+ the :term:`request` will consist of ``{'tag':'1'}``.
In this example we've again associated each of our routes with a :term:`view
-callable` directly. In all cases, the request, which will have a
-``matchdict`` attribute detailing the information found in the URL by the
-process will be passed to the view callable.
+callable` directly. In all cases, the request, which will have a ``matchdict``
+attribute detailing the information found in the URL by the process will be
+passed to the view callable.
Example 3
~~~~~~~~~
-The :term:`context` resource object passed in to a view found as the result
-of URL dispatch will, by default, be an instance of the object returned by
-the :term:`root factory` configured at startup time (the ``root_factory``
-argument to the :term:`Configurator` used to configure the application).
+The :term:`context` resource object passed in to a view found as the result of
+URL dispatch will, by default, be an instance of the object returned by the
+:term:`root factory` configured at startup time (the ``root_factory`` argument
+to the :term:`Configurator` used to configure the application).
You can override this behavior by passing in a ``factory`` argument to the
:meth:`~pyramid.config.Configurator.add_route` method for a particular route.
-The ``factory`` should be a callable that accepts a :term:`request` and
-returns an instance of a class that will be the context resource used by the
-view.
+The ``factory`` should be a callable that accepts a :term:`request` and returns
+an instance of a class that will be the context resource used by the view.
An example of using a route with a factory:
@@ -685,9 +680,9 @@ Or provide the literal string ``/`` as the pattern:
Generating Route URLs
---------------------
-Use the :meth:`pyramid.request.Request.route_url` method to generate URLs
-based on route patterns. For example, if you've configured a route with the
-``name`` "foo" and the ``pattern`` "{a}/{b}/{c}", you might do this.
+Use the :meth:`pyramid.request.Request.route_url` method to generate URLs based
+on route patterns. For example, if you've configured a route with the ``name``
+"foo" and the ``pattern`` "{a}/{b}/{c}", you might do this.
.. code-block:: python
:linenos:
@@ -707,13 +702,12 @@ To generate only the *path* portion of a URL from a route, use the
This will return the string ``/1/2/3`` rather than a full URL.
-Replacement values passed to ``route_url`` or ``route_path`` must be Unicode
-or bytestrings encoded in UTF-8. One exception to this rule exists: if
-you're trying to replace a "remainder" match value (a ``*stararg``
-replacement value), the value may be a tuple containing Unicode strings or
-UTF-8 strings.
+Replacement values passed to ``route_url`` or ``route_path`` must be Unicode or
+bytestrings encoded in UTF-8. One exception to this rule exists: if you're
+trying to replace a "remainder" match value (a ``*stararg`` replacement value),
+the value may be a tuple containing Unicode strings or UTF-8 strings.
-Note that URLs and paths generated by ``route_path`` and ``route_url`` are
+Note that URLs and paths generated by ``route_url`` and ``route_path`` are
always URL-quoted string types (they contain no non-ASCII characters).
Therefore, if you've added a route like so:
@@ -727,7 +721,7 @@ And you later generate a URL using ``route_path`` or ``route_url`` like so:
url = request.route_path('la', city=u'Québec')
-You will wind up with the path encoded to UTF-8 and URL quoted like so:
+You will wind up with the path encoded to UTF-8 and URL-quoted like so:
.. code-block:: text
@@ -759,7 +753,7 @@ You can get a similar result by passing a tuple composed of path elements:
url = request.route_path('abc', foo=(u'Québec', u'biz'))
-Each value in the tuple will be url-quoted and joined by slashes in this case:
+Each value in the tuple will be URL-quoted and joined by slashes in this case:
.. code-block:: text
@@ -793,7 +787,7 @@ ignored when ``static`` is ``True``.
:ref:`External routes <external_route_narr>` are implicitly static.
.. versionadded:: 1.1
- the ``static`` argument to :meth:`~pyramid.config.Configurator.add_route`
+ the ``static`` argument to :meth:`~pyramid.config.Configurator.add_route`.
.. _external_route_narr:
@@ -836,13 +830,13 @@ argument to :meth:`pyramid.config.Configurator.add_notfound_view` or the
equivalent ``append_slash`` argument to the
:class:`pyramid.view.notfound_view_config` decorator.
-Adding ``append_slash=True`` is a way to automatically redirect requests
-where the URL lacks a trailing slash, but requires one to match the proper
-route. When configured, along with at least one other route in your
-application, this view will be invoked if the value of ``PATH_INFO`` does not
-already end in a slash, and if the value of ``PATH_INFO`` *plus* a slash
-matches any route's pattern. In this case it does an HTTP redirect to the
-slash-appended ``PATH_INFO``. In addition you may pass anything that implements
+Adding ``append_slash=True`` is a way to automatically redirect requests where
+the URL lacks a trailing slash, but requires one to match the proper route.
+When configured, along with at least one other route in your application, this
+view will be invoked if the value of ``PATH_INFO`` does not already end in a
+slash, and if the value of ``PATH_INFO`` *plus* a slash matches any route's
+pattern. In this case it does an HTTP redirect to the slash-appended
+``PATH_INFO``. In addition you may pass anything that implements
:class:`pyramid.interfaces.IResponse` which will then be used in place of the
default class (:class:`pyramid.httpexceptions.HTTPFound`).
@@ -872,12 +866,11 @@ application:
config.add_notfound_view(notfound, append_slash=True)
If a request enters the application with the ``PATH_INFO`` value of
-``/no_slash``, the first route will match and the browser will show "No
-slash". However, if a request enters the application with the ``PATH_INFO``
-value of ``/no_slash/``, *no* route will match, and the slash-appending not
-found view will not find a matching route with an appended slash. As a
-result, the ``notfound`` view will be called and it will return a "Not found,
-bro." body.
+``/no_slash``, the first route will match and the browser will show "No slash".
+However, if a request enters the application with the ``PATH_INFO`` value of
+``/no_slash/``, *no* route will match, and the slash-appending not found view
+will not find a matching route with an appended slash. As a result, the
+``notfound`` view will be called and it will return a "Not found, bro." body.
If a request enters the application with the ``PATH_INFO`` value of
``/has_slash/``, the second route will match. If a request enters the
@@ -934,10 +927,10 @@ Debugging Route Matching
It's useful to be able to take a peek under the hood when requests that enter
your application aren't matching your routes as you expect them to. To debug
-route matching, use the ``PYRAMID_DEBUG_ROUTEMATCH`` environment variable or the
-``pyramid.debug_routematch`` configuration file setting (set either to ``true``).
-Details of the route matching decision for a particular request to the
-:app:`Pyramid` application will be printed to the ``stderr`` of the console
+route matching, use the ``PYRAMID_DEBUG_ROUTEMATCH`` environment variable or
+the ``pyramid.debug_routematch`` configuration file setting (set either to
+``true``). Details of the route matching decision for a particular request to
+the :app:`Pyramid` application will be printed to the ``stderr`` of the console
which you started the application from. For example:
.. code-block:: text
@@ -954,11 +947,11 @@ which you started the application from. For example:
http://localhost:6543/static/logo.png; \
route_name: 'static/', ....
-See :ref:`environment_chapter` for more information about how, and where to
-set these values.
+See :ref:`environment_chapter` for more information about how and where to set
+these values.
-You can also use the ``proutes`` command to see a display of all the
-routes configured in your application; for more information, see
+You can also use the ``proutes`` command to see a display of all the routes
+configured in your application. For more information, see
:ref:`displaying_application_routes`.
.. _route_prefix:
@@ -979,11 +972,11 @@ named ``route_prefix`` which can be useful to authors of URL-dispatch-based
applications. If ``route_prefix`` is supplied to the include method, it must
be a string. This string represents a route prefix that will be prepended to
all route patterns added by the *included* configuration. Any calls to
-:meth:`pyramid.config.Configurator.add_route` within the included callable
-will have their pattern prefixed with the value of ``route_prefix``. This can
-be used to help mount a set of routes at a different location than the
-included callable's author intended while still maintaining the same route
-names. For example:
+:meth:`pyramid.config.Configurator.add_route` within the included callable will
+have their pattern prefixed with the value of ``route_prefix``. This can be
+used to help mount a set of routes at a different location than the included
+callable's author intended while still maintaining the same route names. For
+example:
.. code-block:: python
:linenos:
@@ -998,15 +991,15 @@ names. For example:
config.include(users_include, route_prefix='/users')
In the above configuration, the ``show_users`` route will have an effective
-route pattern of ``/users/show``, instead of ``/show`` because the
+route pattern of ``/users/show`` instead of ``/show`` because the
``route_prefix`` argument will be prepended to the pattern. The route will
then only match if the URL path is ``/users/show``, and when the
:meth:`pyramid.request.Request.route_url` function is called with the route
name ``show_users``, it will generate a URL with that same path.
Route prefixes are recursive, so if a callable executed via an include itself
-turns around and includes another callable, the second-level route prefix
-will be prepended with the first:
+turns around and includes another callable, the second-level route prefix will
+be prepended with the first:
.. code-block:: python
:linenos:
@@ -1025,15 +1018,15 @@ will be prepended with the first:
config.include(users_include, route_prefix='/users')
In the above configuration, the ``show_users`` route will still have an
-effective route pattern of ``/users/show``. The ``show_times`` route
-however, will have an effective pattern of ``/users/timing/times``.
+effective route pattern of ``/users/show``. The ``show_times`` route, however,
+will have an effective pattern of ``/users/timing/times``.
-Route prefixes have no impact on the requirement that the set of route
-*names* in any given Pyramid configuration must be entirely unique. If you
-compose your URL dispatch application out of many small subapplications using
-:meth:`pyramid.config.Configurator.include`, it's wise to use a dotted name
-for your route names, so they'll be unlikely to conflict with other packages
-that may be added in the future. For example:
+Route prefixes have no impact on the requirement that the set of route *names*
+in any given Pyramid configuration must be entirely unique. If you compose
+your URL dispatch application out of many small subapplications using
+:meth:`pyramid.config.Configurator.include`, it's wise to use a dotted name for
+your route names so they'll be unlikely to conflict with other packages that
+may be added in the future. For example:
.. code-block:: python
:linenos:
@@ -1060,15 +1053,16 @@ Custom Route Predicates
-----------------------
Each of the predicate callables fed to the ``custom_predicates`` argument of
-:meth:`~pyramid.config.Configurator.add_route` must be a callable accepting
-two arguments. The first argument passed to a custom predicate is a
-dictionary conventionally named ``info``. The second argument is the current
+:meth:`~pyramid.config.Configurator.add_route` must be a callable accepting two
+arguments. The first argument passed to a custom predicate is a dictionary
+conventionally named ``info``. The second argument is the current
:term:`request` object.
-The ``info`` dictionary has a number of contained values: ``match`` is a
-dictionary: it represents the arguments matched in the URL by the route.
-``route`` is an object representing the route which was matched (see
-:class:`pyramid.interfaces.IRoute` for the API of such a route object).
+The ``info`` dictionary has a number of contained values, including ``match``
+and ``route``. ``match`` is a dictionary which represents the arguments matched
+in the URL by the route. ``route`` is an object representing the route which
+was matched (see :class:`pyramid.interfaces.IRoute` for the API of such a route
+object).
``info['match']`` is useful when predicates need access to the route match.
For example:
@@ -1118,9 +1112,9 @@ instance, a predicate might do some type conversion of values:
config.add_route('ymd', '/{year}/{month}/{day}',
custom_predicates=(ymd_to_int,))
-Note that a conversion predicate is still a predicate so it must return
-``True`` or ``False``; a predicate that does *only* conversion, such as the
-one we demonstrate above should unconditionally return ``True``.
+Note that a conversion predicate is still a predicate, so it must return
+``True`` or ``False``. A predicate that does *only* conversion, such as the one
+we demonstrate above, should unconditionally return ``True``.
To avoid the try/except uncertainty, the route pattern can contain regular
expressions specifying requirements for that marker. For instance:
@@ -1141,31 +1135,31 @@ expressions specifying requirements for that marker. For instance:
config.add_route('ymd', '/{year:\d+}/{month:\d+}/{day:\d+}',
custom_predicates=(ymd_to_int,))
-Now the try/except is no longer needed because the route will not match at
-all unless these markers match ``\d+`` which requires them to be valid digits
-for an ``int`` type conversion.
+Now the try/except is no longer needed because the route will not match at all
+unless these markers match ``\d+`` which requires them to be valid digits for
+an ``int`` type conversion.
-The ``match`` dictionary passed within ``info`` to each predicate attached to
-a route will be the same dictionary. Therefore, when registering a custom
-predicate which modifies the ``match`` dict, the code registering the
-predicate should usually arrange for the predicate to be the *last* custom
-predicate in the custom predicate list. Otherwise, custom predicates which
-fire subsequent to the predicate which performs the ``match`` modification
-will receive the *modified* match dictionary.
+The ``match`` dictionary passed within ``info`` to each predicate attached to a
+route will be the same dictionary. Therefore, when registering a custom
+predicate which modifies the ``match`` dict, the code registering the predicate
+should usually arrange for the predicate to be the *last* custom predicate in
+the custom predicate list. Otherwise, custom predicates which fire subsequent
+to the predicate which performs the ``match`` modification will receive the
+*modified* match dictionary.
.. warning::
It is a poor idea to rely on ordering of custom predicates to build a
conversion pipeline, where one predicate depends on the side effect of
- another. For instance, it's a poor idea to register two custom
- predicates, one which handles conversion of a value to an int, the next
- which handles conversion of that integer to some custom object. Just do
- all that in a single custom predicate.
+ another. For instance, it's a poor idea to register two custom predicates,
+ one which handles conversion of a value to an int, the next which handles
+ conversion of that integer to some custom object. Just do all that in a
+ single custom predicate.
The ``route`` object in the ``info`` dict is an object that has two useful
-attributes: ``name`` and ``pattern``. The ``name`` attribute is the route
-name. The ``pattern`` attribute is the route pattern. An example of using
-the route in a set of route predicates:
+attributes: ``name`` and ``pattern``. The ``name`` attribute is the route name.
+The ``pattern`` attribute is the route pattern. Here's an example of using the
+route in a set of route predicates:
.. code-block:: python
:linenos:
@@ -1180,14 +1174,14 @@ the route in a set of route predicates:
custom_predicates=(twenty_ten,))
The above predicate, when added to a number of route configurations ensures
-that the year match argument is '2010' if and only if the route name is
-'ymd', 'ym', or 'y'.
+that the year match argument is '2010' if and only if the route name is 'ymd',
+'ym', or 'y'.
-You can also caption the predicates by setting the ``__text__``
-attribute. This will help you with the ``pviews`` command (see
+You can also caption the predicates by setting the ``__text__`` attribute. This
+will help you with the ``pviews`` command (see
:ref:`displaying_application_routes`) and the ``pyramid_debugtoolbar``.
-If a predicate is a class just add __text__ property in a standard manner.
+If a predicate is a class, just add ``__text__`` property in a standard manner.
.. code-block:: python
:linenos:
@@ -1199,8 +1193,8 @@ If a predicate is a class just add __text__ property in a standard manner.
class DummyCustomPredicate2(object):
__text__ = 'my custom class predicate'
-If a predicate is a method you'll need to assign it after method declaration
-(see `PEP 232 <http://www.python.org/dev/peps/pep-0232/>`_)
+If a predicate is a method, you'll need to assign it after method declaration
+(see `PEP 232 <http://www.python.org/dev/peps/pep-0232/>`_).
.. code-block:: python
:linenos:
@@ -1209,8 +1203,8 @@ If a predicate is a method you'll need to assign it after method declaration
pass
custom_predicate.__text__ = 'my custom method predicate'
-If a predicate is a classmethod using @classmethod will not work, but you can
-still easily do it by wrapping it in classmethod call.
+If a predicate is a classmethod, using ``@classmethod`` will not work, but you
+can still easily do it by wrapping it in a classmethod call.
.. code-block:: python
:linenos:
@@ -1220,7 +1214,7 @@ still easily do it by wrapping it in classmethod call.
classmethod_predicate.__text__ = 'my classmethod predicate'
classmethod_predicate = classmethod(classmethod_predicate)
-Same will work with staticmethod, just use ``staticmethod`` instead of
+The same will work with ``staticmethod``, using ``staticmethod`` instead of
``classmethod``.
.. seealso::
@@ -1236,10 +1230,10 @@ Same will work with staticmethod, just use ``staticmethod`` instead of
Route Factories
---------------
-Although it is not a particular common need in basic applications, a "route"
-configuration declaration can mention a "factory". When that route matches a
-request, and a factory is attached to a route, the :term:`root factory`
-passed at startup time to the :term:`Configurator` is ignored; instead the
+Although it is not a particularly common need in basic applications, a "route"
+configuration declaration can mention a "factory". When a route matches a
+request, and a factory is attached to the route, the :term:`root factory`
+passed at startup time to the :term:`Configurator` is ignored. Instead the
factory associated with the route is used to generate a :term:`root` object.
This object will usually be used as the :term:`context` resource of the view
callable ultimately found via :term:`view lookup`.
@@ -1255,8 +1249,8 @@ The factory can either be a Python object or a :term:`dotted Python name` (a
string) which points to such a Python object, as it is above.
In this way, each route can use a different factory, making it possible to
-supply a different :term:`context` resource object to the view related to
-each particular route.
+supply a different :term:`context` resource object to the view related to each
+particular route.
A factory must be a callable which accepts a request and returns an arbitrary
Python object. For example, the below class can be used as a factory:
@@ -1268,33 +1262,31 @@ Python object. For example, the below class can be used as a factory:
def __init__(self, request):
pass
-A route factory is actually conceptually identical to the :term:`root
-factory` described at :ref:`the_resource_tree`.
+A route factory is actually conceptually identical to the :term:`root factory`
+described at :ref:`the_resource_tree`.
Supplying a different resource factory for each route is useful when you're
trying to use a :app:`Pyramid` :term:`authorization policy` to provide
-declarative, "context sensitive" security checks; each resource can maintain
-a separate :term:`ACL`, as documented in
-:ref:`using_security_with_urldispatch`. It is also useful when you wish to
-combine URL dispatch with :term:`traversal` as documented within
-:ref:`hybrid_chapter`.
+declarative, "context sensitive" security checks. Each resource can maintain a
+separate :term:`ACL`, as documented in :ref:`using_security_with_urldispatch`.
+It is also useful when you wish to combine URL dispatch with :term:`traversal`
+as documented within :ref:`hybrid_chapter`.
.. index::
pair: URL dispatch; security
.. _using_security_with_urldispatch:
-Using :app:`Pyramid` Security With URL Dispatch
---------------------------------------------------
+Using :app:`Pyramid` Security with URL Dispatch
+-----------------------------------------------
:app:`Pyramid` provides its own security framework which consults an
-:term:`authorization policy` before allowing any application code to be
-called. This framework operates in terms of an access control list, which is
-stored as an ``__acl__`` attribute of a resource object. A common thing to
-want to do is to attach an ``__acl__`` to the resource object dynamically for
-declarative security purposes. You can use the ``factory`` argument that
-points at a factory which attaches a custom ``__acl__`` to an object at its
-creation time.
+:term:`authorization policy` before allowing any application code to be called.
+This framework operates in terms of an access control list, which is stored as
+an ``__acl__`` attribute of a resource object. A common thing to want to do is
+to attach an ``__acl__`` to the resource object dynamically for declarative
+security purposes. You can use the ``factory`` argument that points at a
+factory which attaches a custom ``__acl__`` to an object at its creation time.
Such a ``factory`` might look like so:
@@ -1310,15 +1302,15 @@ Such a ``factory`` might look like so:
If the route ``archives/{article}`` is matched, and the article number is
``1``, :app:`Pyramid` will generate an ``Article`` :term:`context` resource
-with an ACL on it that allows the ``editor`` principal the ``view``
-permission. Obviously you can do more generic things than inspect the routes
-match dict to see if the ``article`` argument matches a particular string;
-our sample ``Article`` factory class is not very ambitious.
+with an ACL on it that allows the ``editor`` principal the ``view`` permission.
+Obviously you can do more generic things than inspect the route's match dict to
+see if the ``article`` argument matches a particular string. Our sample
+``Article`` factory class is not very ambitious.
.. note::
- See :ref:`security_chapter` for more information about
- :app:`Pyramid` security and ACLs.
+ See :ref:`security_chapter` for more information about :app:`Pyramid`
+ security and ACLs.
.. index::
pair: route; view callable lookup details
@@ -1330,10 +1322,9 @@ When a request enters the system which matches the pattern of the route, the
usual result is simple: the view callable associated with the route is
invoked with the request that caused the invocation.
-For most usage, you needn't understand more than this; how it works is an
-implementation detail. In the interest of completeness, however, we'll
-explain how it *does* work in this section. You can skip it if you're
-uninterested.
+For most usage, you needn't understand more than this. How it works is an
+implementation detail. In the interest of completeness, however, we'll explain
+how it *does* work in this section. You can skip it if you're uninterested.
When a view is associated with a route configuration, :app:`Pyramid` ensures
that a :term:`view configuration` is registered that will always be found
@@ -1349,26 +1340,25 @@ when the route pattern is matched during a request. To do so:
- At runtime, when a request causes any route to match, the :term:`request`
object is decorated with the route-specific interface.
-- The fact that the request is decorated with a route-specific interface
- causes the :term:`view lookup` machinery to always use the view callable
- registered using that interface by the route configuration to service
- requests that match the route pattern.
+- The fact that the request is decorated with a route-specific interface causes
+ the :term:`view lookup` machinery to always use the view callable registered
+ using that interface by the route configuration to service requests that
+ match the route pattern.
As we can see from the above description, technically, URL dispatch doesn't
-actually map a URL pattern directly to a view callable. Instead, URL
-dispatch is a :term:`resource location` mechanism. A :app:`Pyramid`
-:term:`resource location` subsystem (i.e., :term:`URL dispatch` or
-:term:`traversal`) finds a :term:`resource` object that is the
-:term:`context` of a :term:`request`. Once the :term:`context` is determined,
-a separate subsystem named :term:`view lookup` is then responsible for
-finding and invoking a :term:`view callable` based on information available
-in the context and the request. When URL dispatch is used, the resource
-location and view lookup subsystems provided by :app:`Pyramid` are still
-being utilized, but in a way which does not require a developer to understand
-either of them in detail.
-
-If no route is matched using :term:`URL dispatch`, :app:`Pyramid` falls back
-to :term:`traversal` to handle the :term:`request`.
+actually map a URL pattern directly to a view callable. Instead URL dispatch
+is a :term:`resource location` mechanism. A :app:`Pyramid` :term:`resource
+location` subsystem (i.e., :term:`URL dispatch` or :term:`traversal`) finds a
+:term:`resource` object that is the :term:`context` of a :term:`request`. Once
+the :term:`context` is determined, a separate subsystem named :term:`view
+lookup` is then responsible for finding and invoking a :term:`view callable`
+based on information available in the context and the request. When URL
+dispatch is used, the resource location and view lookup subsystems provided by
+:app:`Pyramid` are still being utilized, but in a way which does not require a
+developer to understand either of them in detail.
+
+If no route is matched using :term:`URL dispatch`, :app:`Pyramid` falls back to
+:term:`traversal` to handle the :term:`request`.
References
----------
diff --git a/docs/narr/viewconfig.rst b/docs/narr/viewconfig.rst
index 484350b31..a7d0848ca 100644
--- a/docs/narr/viewconfig.rst
+++ b/docs/narr/viewconfig.rst
@@ -10,8 +10,8 @@ View Configuration
.. index::
single: view lookup
-:term:`View lookup` is the :app:`Pyramid` subsystem responsible for finding
-and invoking a :term:`view callable`. :term:`View configuration` controls how
+:term:`View lookup` is the :app:`Pyramid` subsystem responsible for finding and
+invoking a :term:`view callable`. :term:`View configuration` controls how
:term:`view lookup` operates in your application. During any given request,
view configuration information is compared against request data by the view
lookup subsystem in order to find the "best" view callable for that request.
@@ -30,8 +30,8 @@ Mapping a Resource or URL Pattern to a View Callable
A developer makes a :term:`view callable` available for use within a
:app:`Pyramid` application via :term:`view configuration`. A view
configuration associates a view callable with a set of statements that
-determine the set of circumstances which must be true for the view callable
-to be invoked.
+determine the set of circumstances which must be true for the view callable to
+be invoked.
A view configuration statement is made about information present in the
:term:`context` resource and the :term:`request`.
@@ -56,35 +56,34 @@ View Configuration Parameters
All forms of view configuration accept the same general types of arguments.
Many arguments supplied during view configuration are :term:`view predicate`
-arguments. View predicate arguments used during view configuration are used
-to narrow the set of circumstances in which :term:`view lookup` will find a
+arguments. View predicate arguments used during view configuration are used to
+narrow the set of circumstances in which :term:`view lookup` will find a
particular view callable.
:term:`View predicate` attributes are an important part of view configuration
that enables the :term:`view lookup` subsystem to find and invoke the
-appropriate view. The greater the number of predicate attributes possessed by a
-view's configuration, the more specific the circumstances need to be before
-the registered view callable will be invoked. The fewer the number of predicates
-which are supplied to a particular view configuration, the more likely it is
-that the associated view callable will be invoked. A view with five
-predicates will always be found and evaluated before a view with two, for
+appropriate view. The greater the number of predicate attributes possessed by
+a view's configuration, the more specific the circumstances need to be before
+the registered view callable will be invoked. The fewer the number of
+predicates which are supplied to a particular view configuration, the more
+likely it is that the associated view callable will be invoked. A view with
+five predicates will always be found and evaluated before a view with two, for
example.
-This does not mean however, that :app:`Pyramid` "stops looking" when it
-finds a view registration with predicates that don't match. If one set
-of view predicates does not match, the "next most specific" view (if
-any) is consulted for predicates, and so on, until a view is found, or
-no view can be matched up with the request. The first view with a set
-of predicates all of which match the request environment will be
-invoked.
+This does not mean however, that :app:`Pyramid` "stops looking" when it finds a
+view registration with predicates that don't match. If one set of view
+predicates does not match, the "next most specific" view (if any) is consulted
+for predicates, and so on, until a view is found, or no view can be matched up
+with the request. The first view with a set of predicates all of which match
+the request environment will be invoked.
If no view can be found with predicates which allow it to be matched up with
the request, :app:`Pyramid` will return an error to the user's browser,
representing a "not found" (404) page. See :ref:`changing_the_notfound_view`
for more information about changing the default :term:`Not Found View`.
-Other view configuration arguments are non-predicate arguments. These tend
-to modify the response of the view callable or prevent the view callable from
+Other view configuration arguments are non-predicate arguments. These tend to
+modify the response of the view callable or prevent the view callable from
being invoked due to an authorization policy. The presence of non-predicate
arguments in a view configuration does not narrow the circumstances in which
the view callable will be invoked.
@@ -96,56 +95,55 @@ Non-Predicate Arguments
``permission``
The name of a :term:`permission` that the user must possess in order to
- invoke the :term:`view callable`. See :ref:`view_security_section` for
- more information about view security and permissions.
+ invoke the :term:`view callable`. See :ref:`view_security_section` for more
+ information about view security and permissions.
- If ``permission`` is not supplied, no permission is registered for this
- view (it's accessible by any caller).
+ If ``permission`` is not supplied, no permission is registered for this view
+ (it's accessible by any caller).
``attr``
The view machinery defaults to using the ``__call__`` method of the
:term:`view callable` (or the function itself, if the view callable is a
function) to obtain a response. The ``attr`` value allows you to vary the
- method attribute used to obtain the response. For example, if your view
- was a class, and the class has a method named ``index`` and you wanted to
- use this method instead of the class's ``__call__`` method to return the
- response, you'd say ``attr="index"`` in the view configuration for the
- view. This is most useful when the view definition is a class.
+ method attribute used to obtain the response. For example, if your view was
+ a class, and the class has a method named ``index`` and you wanted to use
+ this method instead of the class's ``__call__`` method to return the
+ response, you'd say ``attr="index"`` in the view configuration for the view.
+ This is most useful when the view definition is a class.
If ``attr`` is not supplied, ``None`` is used (implying the function itself
- if the view is a function, or the ``__call__`` callable attribute if the
- view is a class).
+ if the view is a function, or the ``__call__`` callable attribute if the view
+ is a class).
``renderer``
- Denotes the :term:`renderer` implementation which will be used to construct
- a :term:`response` from the associated view callable's return value.
+ Denotes the :term:`renderer` implementation which will be used to construct a
+ :term:`response` from the associated view callable's return value.
.. seealso:: See also :ref:`renderers_chapter`.
- This is either a single string term (e.g. ``json``) or a string implying a
- path or :term:`asset specification` (e.g. ``templates/views.pt``) naming a
- :term:`renderer` implementation. If the ``renderer`` value does not
- contain a dot (``.``), the specified string will be used to look up a
- renderer implementation, and that renderer implementation will be used to
- construct a response from the view return value. If the ``renderer`` value
- contains a dot (``.``), the specified term will be treated as a path, and
- the filename extension of the last element in the path will be used to look
- up the renderer implementation, which will be passed the full path.
-
- When the renderer is a path, although a path is usually just a simple
- relative pathname (e.g. ``templates/foo.pt``, implying that a template
- named "foo.pt" is in the "templates" directory relative to the directory of
- the current :term:`package`), a path can be absolute, starting with a slash
- on UNIX or a drive letter prefix on Windows. The path can alternately be a
- :term:`asset specification` in the form
- ``some.dotted.package_name:relative/path``, making it possible to address
- template assets which live in a separate package.
+ This is either a single string term (e.g., ``json``) or a string implying a
+ path or :term:`asset specification` (e.g., ``templates/views.pt``) naming a
+ :term:`renderer` implementation. If the ``renderer`` value does not contain
+ a dot (``.``), the specified string will be used to look up a renderer
+ implementation, and that renderer implementation will be used to construct a
+ response from the view return value. If the ``renderer`` value contains a
+ dot (``.``), the specified term will be treated as a path, and the filename
+ extension of the last element in the path will be used to look up the
+ renderer implementation, which will be passed the full path.
+
+ When the renderer is a path—although a path is usually just a simple relative
+ pathname (e.g., ``templates/foo.pt``, implying that a template named "foo.pt"
+ is in the "templates" directory relative to the directory of the current
+ :term:`package`)—the path can be absolute, starting with a slash on UNIX or a
+ drive letter prefix on Windows. The path can alternatively be a :term:`asset
+ specification` in the form ``some.dotted.package_name:relative/path``, making
+ it possible to address template assets which live in a separate package.
The ``renderer`` attribute is optional. If it is not defined, the "null"
renderer is assumed (no rendering is performed and the value is passed back
- to the upstream :app:`Pyramid` machinery unchanged). Note that if the
- view callable itself returns a :term:`response` (see :ref:`the_response`),
- the specified renderer implementation is never called.
+ to the upstream :app:`Pyramid` machinery unchanged). Note that if the view
+ callable itself returns a :term:`response` (see :ref:`the_response`), the
+ specified renderer implementation is never called.
``http_cache``
When you supply an ``http_cache`` value to a view configuration, the
@@ -153,38 +151,36 @@ Non-Predicate Arguments
associated view callable are modified. The value for ``http_cache`` may be
one of the following:
- - A nonzero integer. If it's a nonzero integer, it's treated as a number
- of seconds. This number of seconds will be used to compute the
- ``Expires`` header and the ``Cache-Control: max-age`` parameter of
- responses to requests which call this view. For example:
- ``http_cache=3600`` instructs the requesting browser to 'cache this
- response for an hour, please'.
+ - A nonzero integer. If it's a nonzero integer, it's treated as a number of
+ seconds. This number of seconds will be used to compute the ``Expires``
+ header and the ``Cache-Control: max-age`` parameter of responses to
+ requests which call this view. For example: ``http_cache=3600`` instructs
+ the requesting browser to 'cache this response for an hour, please'.
- A ``datetime.timedelta`` instance. If it's a ``datetime.timedelta``
- instance, it will be converted into a number of seconds, and that number
- of seconds will be used to compute the ``Expires`` header and the
+ instance, it will be converted into a number of seconds, and that number of
+ seconds will be used to compute the ``Expires`` header and the
``Cache-Control: max-age`` parameter of responses to requests which call
this view. For example: ``http_cache=datetime.timedelta(days=1)``
instructs the requesting browser to 'cache this response for a day,
please'.
- - Zero (``0``). If the value is zero, the ``Cache-Control`` and
- ``Expires`` headers present in all responses from this view will be
- composed such that client browser cache (and any intermediate caches) are
- instructed to never cache the response.
-
- - A two-tuple. If it's a two tuple (e.g. ``http_cache=(1,
- {'public':True})``), the first value in the tuple may be a nonzero
- integer or a ``datetime.timedelta`` instance; in either case this value
- will be used as the number of seconds to cache the response. The second
- value in the tuple must be a dictionary. The values present in the
- dictionary will be used as input to the ``Cache-Control`` response
- header. For example: ``http_cache=(3600, {'public':True})`` means 'cache
- for an hour, and add ``public`` to the Cache-Control header of the
- response'. All keys and values supported by the
- ``webob.cachecontrol.CacheControl`` interface may be added to the
- dictionary. Supplying ``{'public':True}`` is equivalent to calling
- ``response.cache_control.public = True``.
+ - Zero (``0``). If the value is zero, the ``Cache-Control`` and ``Expires``
+ headers present in all responses from this view will be composed such that
+ client browser cache (and any intermediate caches) are instructed to never
+ cache the response.
+
+ - A two-tuple. If it's a two-tuple (e.g., ``http_cache=(1,
+ {'public':True})``), the first value in the tuple may be a nonzero integer
+ or a ``datetime.timedelta`` instance. In either case this value will be
+ used as the number of seconds to cache the response. The second value in
+ the tuple must be a dictionary. The values present in the dictionary will
+ be used as input to the ``Cache-Control`` response header. For example:
+ ``http_cache=(3600, {'public':True})`` means 'cache for an hour, and add
+ ``public`` to the Cache-Control header of the response'. All keys and
+ values supported by the ``webob.cachecontrol.CacheControl`` interface may
+ be added to the dictionary. Supplying ``{'public':True}`` is equivalent to
+ calling ``response.cache_control.public = True``.
Providing a non-tuple value as ``http_cache`` is equivalent to calling
``response.cache_expires(value)`` within your view's body.
@@ -192,9 +188,9 @@ Non-Predicate Arguments
Providing a two-tuple value as ``http_cache`` is equivalent to calling
``response.cache_expires(value[0], **value[1])`` within your view's body.
- If you wish to avoid influencing, the ``Expires`` header, and instead wish
- to only influence ``Cache-Control`` headers, pass a tuple as ``http_cache``
- with the first element of ``None``, e.g.: ``(None, {'public':True})``.
+ If you wish to avoid influencing the ``Expires`` header, and instead wish to
+ only influence ``Cache-Control`` headers, pass a tuple as ``http_cache`` with
+ the first element of ``None``, i.e., ``(None, {'public':True})``.
``wrapper``
The :term:`view name` of a different :term:`view configuration` which will
@@ -203,24 +199,24 @@ Non-Predicate Arguments
this view as the ``request.wrapped_response`` attribute of its own request.
Using a wrapper makes it possible to "chain" views together to form a
composite response. The response of the outermost wrapper view will be
- returned to the user. The wrapper view will be found as any view is found:
- see :ref:`view_lookup`. The "best" wrapper view will be found based on the
- lookup ordering: "under the hood" this wrapper view is looked up via
+ returned to the user. The wrapper view will be found as any view is found.
+ See :ref:`view_lookup`. The "best" wrapper view will be found based on the
+ lookup ordering. "Under the hood" this wrapper view is looked up via
``pyramid.view.render_view_to_response(context, request,
- 'wrapper_viewname')``. The context and request of a wrapper view is the
- same context and request of the inner view.
+ 'wrapper_viewname')``. The context and request of a wrapper view is the same
+ context and request of the inner view.
If ``wrapper`` is not supplied, no wrapper view is used.
``decorator``
A :term:`dotted Python name` to a function (or the function itself) which
- will be used to decorate the registered :term:`view callable`. The
- decorator function will be called with the view callable as a single
- argument. The view callable it is passed will accept ``(context,
- request)``. The decorator must return a replacement view callable which
- also accepts ``(context, request)``. The ``decorator`` may also be an
- iterable of decorators, in which case they will be applied one after the
- other to the view, in reverse order. For example::
+ will be used to decorate the registered :term:`view callable`. The decorator
+ function will be called with the view callable as a single argument. The
+ view callable it is passed will accept ``(context, request)``. The decorator
+ must return a replacement view callable which also accepts ``(context,
+ request)``. The ``decorator`` may also be an iterable of decorators, in which
+ case they will be applied one after the other to the view, in reverse order.
+ For example::
@view_config(..., decorator=(decorator2, decorator1))
def myview(request):
@@ -253,33 +249,32 @@ Non-Predicate Arguments
A Python object or :term:`dotted Python name` which refers to a :term:`view
mapper`, or ``None``. By default it is ``None``, which indicates that the
view should use the default view mapper. This plug-point is useful for
- Pyramid extension developers, but it's not very useful for 'civilians' who
+ Pyramid extension developers, but it's not very useful for "civilians" who
are just developing stock Pyramid applications. Pay no attention to the man
behind the curtain.
Predicate Arguments
+++++++++++++++++++
-These arguments modify view lookup behavior. In general, the more predicate
-arguments that are supplied, the more specific, and narrower the usage of the
+These arguments modify view lookup behavior. In general the more predicate
+arguments that are supplied, the more specific and narrower the usage of the
configured view.
``name``
The :term:`view name` required to match this view callable. A ``name``
- argument is typically only used when your application uses
- :term:`traversal`. Read :ref:`traversal_chapter` to understand the concept
- of a view name.
+ argument is typically only used when your application uses :term:`traversal`.
+ Read :ref:`traversal_chapter` to understand the concept of a view name.
If ``name`` is not supplied, the empty string is used (implying the default
view).
``context``
- An object representing a Python class that the :term:`context` resource
- must be an instance of *or* the :term:`interface` that the :term:`context`
+ An object representing a Python class of which the :term:`context` resource
+ must be an instance *or* the :term:`interface` that the :term:`context`
resource must provide in order for this view to be found and called. This
predicate is true when the :term:`context` resource is an instance of the
- represented class or if the :term:`context` resource provides the
- represented interface; it is otherwise false.
+ represented class or if the :term:`context` resource provides the represented
+ interface; it is otherwise false.
If ``context`` is not supplied, the value ``None``, which matches any
resource, is used.
@@ -289,68 +284,68 @@ configured view.
the named route has matched.
This value must match the ``name`` of a :term:`route configuration`
- declaration (see :ref:`urldispatch_chapter`) that must match before this
- view will be called. Note that the ``route`` configuration referred to by
+ declaration (see :ref:`urldispatch_chapter`) that must match before this view
+ will be called. Note that the ``route`` configuration referred to by
``route_name`` will usually have a ``*traverse`` token in the value of its
``pattern``, representing a part of the path that will be used by
:term:`traversal` against the result of the route's :term:`root factory`.
If ``route_name`` is not supplied, the view callable will only have a chance
of being invoked if no other route was matched. This is when the
- request/context pair found via :term:`resource location` does not indicate
- it matched any configured route.
+ request/context pair found via :term:`resource location` does not indicate it
+ matched any configured route.
``request_type``
This value should be an :term:`interface` that the :term:`request` must
provide in order for this view to be found and called.
- If ``request_type`` is not supplied, the value ``None`` is used, implying
- any request type.
+ If ``request_type`` is not supplied, the value ``None`` is used, implying any
+ request type.
*This is an advanced feature, not often used by "civilians"*.
``request_method``
This value can be either a string (such as ``"GET"``, ``"POST"``,
- ``"PUT"``, ``"DELETE"``, ``"HEAD"`` or ``"OPTIONS"``) representing an
- HTTP ``REQUEST_METHOD``, or a tuple containing one or more of these
- strings. A view declaration with this argument ensures that the
- view will only be called when the ``method`` attribute of the
- request (aka the ``REQUEST_METHOD`` of the WSGI environment) matches
- a supplied value. Note that use of ``"GET"`` also implies that the
- view will respond to ``"HEAD"`` as of Pyramid 1.4.
-
- If ``request_method`` is not supplied, the view will be invoked regardless
- of the ``REQUEST_METHOD`` of the :term:`WSGI` environment.
+ ``"PUT"``, ``"DELETE"``, ``"HEAD"``, or ``"OPTIONS"``) representing an HTTP
+ ``REQUEST_METHOD`` or a tuple containing one or more of these strings. A
+ view declaration with this argument ensures that the view will only be called
+ when the ``method`` attribute of the request (i.e., the ``REQUEST_METHOD`` of
+ the WSGI environment) matches a supplied value.
+
+ .. versionchanged:: 1.4
+ The use of ``"GET"`` also implies that the view will respond to ``"HEAD"``.
+
+ If ``request_method`` is not supplied, the view will be invoked regardless of
+ the ``REQUEST_METHOD`` of the :term:`WSGI` environment.
``request_param``
This value can be any string or a sequence of strings. A view declaration
with this argument ensures that the view will only be called when the
:term:`request` has a key in the ``request.params`` dictionary (an HTTP
- ``GET`` or ``POST`` variable) that has a name which matches the
- supplied value.
+ ``GET`` or ``POST`` variable) that has a name which matches the supplied
+ value.
- If any value supplied has a ``=`` sign in it,
- e.g. ``request_param="foo=123"``, then the key (``foo``) must both exist
- in the ``request.params`` dictionary, *and* the value must match the right
- hand side of the expression (``123``) for the view to "match" the current
- request.
+ If any value supplied has an ``=`` sign in it, e.g.,
+ ``request_param="foo=123"``, then the key (``foo``) must both exist in the
+ ``request.params`` dictionary, *and* the value must match the right hand side
+ of the expression (``123``) for the view to "match" the current request.
If ``request_param`` is not supplied, the view will be invoked without
consideration of keys and values in the ``request.params`` dictionary.
``match_param``
- This param may be either a single string of the format "key=value" or a
- tuple containing one or more of these strings.
+ This param may be either a single string of the format "key=value" or a tuple
+ containing one or more of these strings.
This argument ensures that the view will only be called when the
- :term:`request` has key/value pairs in its :term:`matchdict` that equal
- those supplied in the predicate. e.g. ``match_param="action=edit"`` would
+ :term:`request` has key/value pairs in its :term:`matchdict` that equal those
+ supplied in the predicate. For example, ``match_param="action=edit"`` would
require the ``action`` parameter in the :term:`matchdict` match the right
hand side of the expression (``edit``) for the view to "match" the current
request.
- If the ``match_param`` is a tuple, every key/value pair must match
- for the predicate to pass.
+ If the ``match_param`` is a tuple, every key/value pair must match for the
+ predicate to pass.
If ``match_param`` is not supplied, the view will be invoked without
consideration of the keys and values in ``request.matchdict``.
@@ -358,41 +353,40 @@ configured view.
.. versionadded:: 1.2
``containment``
- This value should be a reference to a Python class or :term:`interface`
- that a parent object in the context resource's :term:`lineage` must provide
- in order for this view to be found and called. The resources in your
- resource tree must be "location-aware" to use this feature.
+ This value should be a reference to a Python class or :term:`interface` that
+ a parent object in the context resource's :term:`lineage` must provide in
+ order for this view to be found and called. The resources in your resource
+ tree must be "location-aware" to use this feature.
- If ``containment`` is not supplied, the interfaces and classes in the
- lineage are not considered when deciding whether or not to invoke the view
- callable.
+ If ``containment`` is not supplied, the interfaces and classes in the lineage
+ are not considered when deciding whether or not to invoke the view callable.
See :ref:`location_aware` for more information about location-awareness.
``xhr``
This value should be either ``True`` or ``False``. If this value is
specified and is ``True``, the :term:`WSGI` environment must possess an
- ``HTTP_X_REQUESTED_WITH`` (aka ``X-Requested-With``) header that has the
+ ``HTTP_X_REQUESTED_WITH`` header (i.e., ``X-Requested-With``) that has the
value ``XMLHttpRequest`` for the associated view callable to be found and
called. This is useful for detecting AJAX requests issued from jQuery,
- Prototype and other Javascript libraries.
+ Prototype, and other Javascript libraries.
- If ``xhr`` is not specified, the ``HTTP_X_REQUESTED_WITH`` HTTP header is
- not taken into consideration when deciding whether or not to invoke the
+ If ``xhr`` is not specified, the ``HTTP_X_REQUESTED_WITH`` HTTP header is not
+ taken into consideration when deciding whether or not to invoke the
associated view callable.
``accept``
- The value of this argument represents a match query for one or more
- mimetypes in the ``Accept`` HTTP request header. If this value is
- specified, it must be in one of the following forms: a mimetype match token
- in the form ``text/plain``, a wildcard mimetype match token in the form
- ``text/*`` or a match-all wildcard mimetype match token in the form
- ``*/*``. If any of the forms matches the ``Accept`` header of the request,
- this predicate will be true.
-
- If ``accept`` is not specified, the ``HTTP_ACCEPT`` HTTP header is not
- taken into consideration when deciding whether or not to invoke the
- associated view callable.
+ The value of this argument represents a match query for one or more mimetypes
+ in the ``Accept`` HTTP request header. If this value is specified, it must
+ be in one of the following forms: a mimetype match token in the form
+ ``text/plain``, a wildcard mimetype match token in the form ``text/*``, or a
+ match-all wildcard mimetype match token in the form ``*/*``. If any of the
+ forms matches the ``Accept`` header of the request, this predicate will be
+ true.
+
+ If ``accept`` is not specified, the ``HTTP_ACCEPT`` HTTP header is not taken
+ into consideration when deciding whether or not to invoke the associated view
+ callable.
``header``
This value represents an HTTP header name or a header name/value pair.
@@ -400,94 +394,92 @@ configured view.
If ``header`` is specified, it must be a header name or a
``headername:headervalue`` pair.
- If ``header`` is specified without a value (a bare header name only,
- e.g. ``If-Modified-Since``), the view will only be invoked if the HTTP
- header exists with any value in the request.
+ If ``header`` is specified without a value (a bare header name only, e.g.,
+ ``If-Modified-Since``), the view will only be invoked if the HTTP header
+ exists with any value in the request.
- If ``header`` is specified, and possesses a name/value pair
- (e.g. ``User-Agent:Mozilla/.*``), the view will only be invoked if the HTTP
- header exists *and* the HTTP header matches the value requested. When the
- ``headervalue`` contains a ``:`` (colon), it will be considered a
- name/value pair (e.g. ``User-Agent:Mozilla/.*`` or ``Host:localhost``).
- The value portion should be a regular expression.
+ If ``header`` is specified, and possesses a name/value pair (e.g.,
+ ``User-Agent:Mozilla/.*``), the view will only be invoked if the HTTP header
+ exists *and* the HTTP header matches the value requested. When the
+ ``headervalue`` contains a ``:`` (colon), it will be considered a name/value
+ pair (e.g., ``User-Agent:Mozilla/.*`` or ``Host:localhost``). The value
+ portion should be a regular expression.
Whether or not the value represents a header name or a header name/value
pair, the case of the header name is not significant.
- If ``header`` is not specified, the composition, presence or absence of
- HTTP headers is not taken into consideration when deciding whether or not
- to invoke the associated view callable.
+ If ``header`` is not specified, the composition, presence, or absence of HTTP
+ headers is not taken into consideration when deciding whether or not to
+ invoke the associated view callable.
``path_info``
This value represents a regular expression pattern that will be tested
- against the ``PATH_INFO`` WSGI environment variable to decide whether or
- not to call the associated view callable. If the regex matches, this
- predicate will be ``True``.
+ against the ``PATH_INFO`` WSGI environment variable to decide whether or not
+ to call the associated view callable. If the regex matches, this predicate
+ will be ``True``.
If ``path_info`` is not specified, the WSGI ``PATH_INFO`` is not taken into
consideration when deciding whether or not to invoke the associated view
callable.
``check_csrf``
- If specified, this value should be one of ``None``, ``True``, ``False``, or
- a string representing the 'check name'. If the value is ``True`` or a
- string, CSRF checking will be performed. If the value is ``False`` or
- ``None``, CSRF checking will not be performed.
+ If specified, this value should be one of ``None``, ``True``, ``False``, or a
+ string representing the "check name". If the value is ``True`` or a string,
+ CSRF checking will be performed. If the value is ``False`` or ``None``, CSRF
+ checking will not be performed.
- If the value provided is a string, that string will be used as the 'check
- name'. If the value provided is ``True``, ``csrf_token`` will be used as
- the check name.
+ If the value provided is a string, that string will be used as the "check
+ name". If the value provided is ``True``, ``csrf_token`` will be used as the
+ check name.
If CSRF checking is performed, the checked value will be the value of
``request.params[check_name]``. This value will be compared against the
value of ``request.session.get_csrf_token()``, and the check will pass if
- these two values are the same. If the check passes, the associated view
- will be permitted to execute. If the check fails, the associated view
- will not be permitted to execute.
+ these two values are the same. If the check passes, the associated view will
+ be permitted to execute. If the check fails, the associated view will not be
+ permitted to execute.
- Note that using this feature requires a :term:`session factory` to have
- been configured.
+ Note that using this feature requires a :term:`session factory` to have been
+ configured.
.. versionadded:: 1.4a2
``physical_path``
If specified, this value should be a string or a tuple representing the
:term:`physical path` of the context found via traversal for this predicate
- to match as true. For example: ``physical_path='/'`` or
- ``physical_path='/a/b/c'`` or ``physical_path=('', 'a', 'b', 'c')``. This is
- not a path prefix match or a regex, it's a whole-path match. It's useful
+ to match as true. For example, ``physical_path='/'``,
+ ``physical_path='/a/b/c'``, or ``physical_path=('', 'a', 'b', 'c')``. This
+ is not a path prefix match or a regex, but a whole-path match. It's useful
when you want to always potentially show a view when some object is traversed
to, but you can't be sure about what kind of object it will be, so you can't
- use the ``context`` predicate. The individual path elements inbetween slash
+ use the ``context`` predicate. The individual path elements between slash
characters or in tuple elements should be the Unicode representation of the
name of the resource and should not be encoded in any way.
.. versionadded:: 1.4a3
``effective_principals``
-
If specified, this value should be a :term:`principal` identifier or a
sequence of principal identifiers. If the
- :meth:`pyramid.request.Request.effective_principals` method indicates that every
- principal named in the argument list is present in the current request, this
- predicate will return True; otherwise it will return False. For example:
- ``effective_principals=pyramid.security.Authenticated`` or
+ :meth:`pyramid.request.Request.effective_principals` method indicates that
+ every principal named in the argument list is present in the current request,
+ this predicate will return True; otherwise it will return False. For
+ example: ``effective_principals=pyramid.security.Authenticated`` or
``effective_principals=('fred', 'group:admins')``.
.. versionadded:: 1.4a4
``custom_predicates``
- If ``custom_predicates`` is specified, it must be a sequence of references
- to custom predicate callables. Use custom predicates when no set of
- predefined predicates do what you need. Custom predicates can be combined
- with predefined predicates as necessary. Each custom predicate callable
- should accept two arguments: ``context`` and ``request`` and should return
- either ``True`` or ``False`` after doing arbitrary evaluation of the
- context resource and/or the request. If all callables return ``True``, the
+ If ``custom_predicates`` is specified, it must be a sequence of references to
+ custom predicate callables. Use custom predicates when no set of predefined
+ predicates do what you need. Custom predicates can be combined with
+ predefined predicates as necessary. Each custom predicate callable should
+ accept two arguments, ``context`` and ``request``, and should return either
+ ``True`` or ``False`` after doing arbitrary evaluation of the context
+ resource and/or the request. If all callables return ``True``, the
associated view callable will be considered viable for a given request.
- If ``custom_predicates`` is not specified, no custom predicates are
- used.
+ If ``custom_predicates`` is not specified, no custom predicates are used.
``predicates``
Pass a key/value pair here to use a third-party predicate registered via
@@ -515,8 +507,8 @@ You can invert the meaning of any predicate value by wrapping it in a call to
request_method=not_('POST')
)
-The above example will ensure that the view is called if the request method
-is *not* ``POST``, at least if no other view is more specific.
+The above example will ensure that the view is called if the request method is
+*not* ``POST``, at least if no other view is more specific.
This technique of wrapping a predicate value in ``not_`` can be used anywhere
predicate values are accepted:
@@ -538,11 +530,11 @@ Adding View Configuration Using the ``@view_config`` Decorator
.. warning::
- Using this feature tends to slow down application startup slightly, as
- more work is performed at application startup to scan for view
- configuration declarations. For maximum startup performance, use the view
- configuration method described in
- :ref:`mapping_views_using_imperative_config_section` instead.
+ Using this feature tends to slow down application startup slightly, as more
+ work is performed at application startup to scan for view configuration
+ declarations. For maximum startup performance, use the view configuration
+ method described in :ref:`mapping_views_using_imperative_config_section`
+ instead.
The :class:`~pyramid.view.view_config` decorator can be used to associate
:term:`view configuration` information with a function, method, or class that
@@ -592,9 +584,8 @@ request method, request type, request param, route name, or containment.
The mere existence of a ``@view_config`` decorator doesn't suffice to perform
view configuration. All that the decorator does is "annotate" the function
with your configuration declarations, it doesn't process them. To make
-:app:`Pyramid` process your :class:`pyramid.view.view_config` declarations,
-you *must* use the ``scan`` method of a
-:class:`pyramid.config.Configurator`:
+:app:`Pyramid` process your :class:`pyramid.view.view_config` declarations, you
+*must* use the ``scan`` method of a :class:`pyramid.config.Configurator`:
.. code-block:: python
:linenos:
@@ -603,9 +594,9 @@ you *must* use the ``scan`` method of a
# pyramid.config.Configurator class
config.scan()
-Please see :ref:`decorations_and_code_scanning` for detailed information
-about what happens when code is scanned for configuration declarations
-resulting from use of decorators like :class:`~pyramid.view.view_config`.
+Please see :ref:`decorations_and_code_scanning` for detailed information about
+what happens when code is scanned for configuration declarations resulting from
+use of decorators like :class:`~pyramid.view.view_config`.
See :ref:`configuration_module` for additional API arguments to the
:meth:`~pyramid.config.Configurator.scan` method. For example, the method
@@ -613,10 +604,10 @@ allows you to supply a ``package`` argument to better control exactly *which*
code will be scanned.
All arguments to the :class:`~pyramid.view.view_config` decorator mean
-precisely the same thing as they would if they were passed as arguments to
-the :meth:`pyramid.config.Configurator.add_view` method save for the ``view``
-argument. Usage of the :class:`~pyramid.view.view_config` decorator is a
-form of :term:`declarative configuration`, while
+precisely the same thing as they would if they were passed as arguments to the
+:meth:`pyramid.config.Configurator.add_view` method save for the ``view``
+argument. Usage of the :class:`~pyramid.view.view_config` decorator is a form
+of :term:`declarative configuration`, while
:meth:`pyramid.config.Configurator.add_view` is a form of :term:`imperative
configuration`. However, they both do the same thing.
@@ -644,8 +635,8 @@ If your view callable is a function, it may be used as a function decorator:
return Response('edited!')
If your view callable is a class, the decorator can also be used as a class
-decorator. All the arguments to the decorator are the same when applied
-against a class as when they are applied against a function. For example:
+decorator. All the arguments to the decorator are the same when applied against
+a class as when they are applied against a function. For example:
.. code-block:: python
:linenos:
@@ -696,15 +687,15 @@ The decorator can also be used against a method of a class:
When the decorator is used against a method of a class, a view is registered
for the *class*, so the class constructor must accept an argument list in one
-of two forms: either it must accept a single argument ``request`` or it must
-accept two arguments, ``context, request``.
+of two forms: either a single argument, ``request``, or two arguments,
+``context, request``.
The method which is decorated must return a :term:`response`.
Using the decorator against a particular method of a class is equivalent to
-using the ``attr`` parameter in a decorator attached to the class itself.
-For example, the above registration implied by the decorator being used
-against the ``amethod`` method could be spelled equivalently as the below:
+using the ``attr`` parameter in a decorator attached to the class itself. For
+example, the above registration implied by the decorator being used against the
+``amethod`` method could be written equivalently as follows:
.. code-block:: python
:linenos:
@@ -730,9 +721,9 @@ Adding View Configuration Using :meth:`~pyramid.config.Configurator.add_view`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The :meth:`pyramid.config.Configurator.add_view` method within
-:ref:`configuration_module` is used to configure a view "imperatively"
-(without a :class:`~pyramid.view.view_config` decorator). The arguments to
-this method are very similar to the arguments that you provide to the
+:ref:`configuration_module` is used to configure a view "imperatively" (without
+a :class:`~pyramid.view.view_config` decorator). The arguments to this method
+are very similar to the arguments that you provide to the
:class:`~pyramid.view.view_config` decorator. For example:
.. code-block:: python
@@ -747,10 +738,10 @@ this method are very similar to the arguments that you provide to the
# pyramid.config.Configurator class
config.add_view(hello_world, route_name='hello')
-The first argument, a :term:`view callable`, is the only required argument.
-It must either be a Python object which is the view itself or a
-:term:`dotted Python name` to such an object.
-In the above example, the ``view callable`` is the ``hello_world`` function.
+The first argument, a :term:`view callable`, is the only required argument. It
+must either be a Python object which is the view itself or a :term:`dotted
+Python name` to such an object. In the above example, the ``view callable`` is
+the ``hello_world`` function.
When you use only :meth:`~pyramid.config.Configurator.add_view` to add view
configurations, you don't need to issue a :term:`scan` in order for the view
@@ -772,7 +763,7 @@ defaults to the view configuration information used by every ``@view_config``
decorator that decorates a method of that class.
For instance, if you've got a class that has methods that represent "REST
-actions", all which are mapped to the same route, but different request
+actions", all of which are mapped to the same route but different request
methods, instead of this:
.. code-block:: python
@@ -824,17 +815,17 @@ You can do this:
return Response('delete')
In the above example, we were able to take the ``route_name='rest'`` argument
-out of the call to each individual ``@view_config`` statement, because we
-used a ``@view_defaults`` class decorator to provide the argument as a
-default to each view method it possessed.
+out of the call to each individual ``@view_config`` statement because we used a
+``@view_defaults`` class decorator to provide the argument as a default to each
+view method it possessed.
Arguments passed to ``@view_config`` will override any default passed to
``@view_defaults``.
The ``view_defaults`` class decorator can also provide defaults to the
:meth:`pyramid.config.Configurator.add_view` directive when a decorated class
-is passed to that directive as its ``view`` argument. For example, instead
-of this:
+is passed to that directive as its ``view`` argument. For example, instead of
+this:
.. code-block:: python
:linenos:
@@ -868,7 +859,7 @@ of this:
To reduce the amount of repetition in the ``config.add_view`` statements, we
can move the ``route_name='rest'`` argument to a ``@view_defaults`` class
-decorator on the RESTView class:
+decorator on the ``RESTView`` class:
.. code-block:: python
:linenos:
@@ -904,8 +895,8 @@ decorator on the RESTView class:
argument passed to ``view_defaults`` provides a default for the view
configurations of methods of the class it's decorating.
-Normal Python inheritance rules apply to defaults added via
-``view_defaults``. For example:
+Normal Python inheritance rules apply to defaults added via ``view_defaults``.
+For example:
.. code-block:: python
:linenos:
@@ -919,8 +910,8 @@ Normal Python inheritance rules apply to defaults added via
The ``Bar`` class above will inherit its view defaults from the arguments
passed to the ``view_defaults`` decorator of the ``Foo`` class. To prevent
-this from happening, use a ``view_defaults`` decorator without any arguments
-on the subclass:
+this from happening, use a ``view_defaults`` decorator without any arguments on
+the subclass:
.. code-block:: python
:linenos:
@@ -946,11 +937,11 @@ Configuring View Security
~~~~~~~~~~~~~~~~~~~~~~~~~
If an :term:`authorization policy` is active, any :term:`permission` attached
-to a :term:`view configuration` found during view lookup will be verified.
-This will ensure that the currently authenticated user possesses that
-permission against the :term:`context` resource before the view function is
-actually called. Here's an example of specifying a permission in a view
-configuration using :meth:`~pyramid.config.Configurator.add_view`:
+to a :term:`view configuration` found during view lookup will be verified. This
+will ensure that the currently authenticated user possesses that permission
+against the :term:`context` resource before the view function is actually
+called. Here's an example of specifying a permission in a view configuration
+using :meth:`~pyramid.config.Configurator.add_view`:
.. code-block:: python
:linenos:
@@ -964,8 +955,8 @@ configuration using :meth:`~pyramid.config.Configurator.add_view`:
When an :term:`authorization policy` is enabled, this view will be protected
with the ``add`` permission. The view will *not be called* if the user does
not possess the ``add`` permission relative to the current :term:`context`.
-Instead the :term:`forbidden view` result will be returned to the client as
-per :ref:`protecting_views`.
+Instead the :term:`forbidden view` result will be returned to the client as per
+:ref:`protecting_views`.
.. index::
single: debugging not found errors
@@ -976,14 +967,14 @@ per :ref:`protecting_views`.
:exc:`~pyramid.exceptions.NotFound` Errors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-It's useful to be able to debug :exc:`~pyramid.exceptions.NotFound`
-error responses when they
-occur unexpectedly due to an application registry misconfiguration. To debug
-these errors, use the ``PYRAMID_DEBUG_NOTFOUND`` environment variable or the
-``pyramid.debug_notfound`` configuration file setting. Details of why a view
-was not found will be printed to ``stderr``, and the browser representation of
-the error will include the same information. See :ref:`environment_chapter`
-for more information about how, and where to set these values.
+It's useful to be able to debug :exc:`~pyramid.exceptions.NotFound` error
+responses when they occur unexpectedly due to an application registry
+misconfiguration. To debug these errors, use the ``PYRAMID_DEBUG_NOTFOUND``
+environment variable or the ``pyramid.debug_notfound`` configuration file
+setting. Details of why a view was not found will be printed to ``stderr``,
+and the browser representation of the error will include the same information.
+See :ref:`environment_chapter` for more information about how, and where to set
+these values.
.. index::
single: HTTP caching
@@ -995,23 +986,23 @@ Influencing HTTP Caching
.. versionadded:: 1.1
-When a non-``None`` ``http_cache`` argument is passed to a view
-configuration, Pyramid will set ``Expires`` and ``Cache-Control`` response
-headers in the resulting response, causing browsers to cache the response
-data for some time. See ``http_cache`` in :ref:`nonpredicate_view_args` for
-the allowable values and what they mean.
-
-Sometimes it's undesirable to have these headers set as the result of
-returning a response from a view, even though you'd like to decorate the view
-with a view configuration decorator that has ``http_cache``. Perhaps there's
-an alternate branch in your view code that returns a response that should
-never be cacheable, while the "normal" branch returns something that should
-always be cacheable. If this is the case, set the ``prevent_auto`` attribute
-of the ``response.cache_control`` object to a non-``False`` value. For
-example, the below view callable is configured with a ``@view_config``
-decorator that indicates any response from the view should be cached for 3600
-seconds. However, the view itself prevents caching from taking place unless
-there's a ``should_cache`` GET or POST variable:
+When a non-``None`` ``http_cache`` argument is passed to a view configuration,
+Pyramid will set ``Expires`` and ``Cache-Control`` response headers in the
+resulting response, causing browsers to cache the response data for some time.
+See ``http_cache`` in :ref:`nonpredicate_view_args` for the allowable values
+and what they mean.
+
+Sometimes it's undesirable to have these headers set as the result of returning
+a response from a view, even though you'd like to decorate the view with a view
+configuration decorator that has ``http_cache``. Perhaps there's an
+alternative branch in your view code that returns a response that should never
+be cacheable, while the "normal" branch returns something that should always be
+cacheable. If this is the case, set the ``prevent_auto`` attribute of the
+``response.cache_control`` object to a non-``False`` value. For example, the
+below view callable is configured with a ``@view_config`` decorator that
+indicates any response from the view should be cached for 3600 seconds.
+However, the view itself prevents caching from taking place unless there's a
+``should_cache`` GET or POST variable:
.. code-block:: python
@@ -1024,19 +1015,19 @@ there's a ``should_cache`` GET or POST variable:
response.cache_control.prevent_auto = True
return response
-Note that the ``http_cache`` machinery will overwrite or add to caching
-headers you set within the view itself unless you use ``prevent_auto``.
+Note that the ``http_cache`` machinery will overwrite or add to caching headers
+you set within the view itself, unless you use ``prevent_auto``.
-You can also turn off the effect of ``http_cache`` entirely for the duration
-of a Pyramid application lifetime. To do so, set the
+You can also turn off the effect of ``http_cache`` entirely for the duration of
+a Pyramid application lifetime. To do so, set the
``PYRAMID_PREVENT_HTTP_CACHE`` environment variable or the
-``pyramid.prevent_http_cache`` configuration value setting to a true value.
-For more information, see :ref:`preventing_http_caching`.
+``pyramid.prevent_http_cache`` configuration value setting to a true value. For
+more information, see :ref:`preventing_http_caching`.
Note that setting ``pyramid.prevent_http_cache`` will have no effect on caching
headers that your application code itself sets. It will only prevent caching
-headers that would have been set by the Pyramid HTTP caching machinery
-invoked as the result of the ``http_cache`` argument to view configuration.
+headers that would have been set by the Pyramid HTTP caching machinery invoked
+as the result of the ``http_cache`` argument to view configuration.
.. index::
pair: view configuration; debugging
diff --git a/docs/narr/views.rst b/docs/narr/views.rst
index a746eb043..770d27919 100644
--- a/docs/narr/views.rst
+++ b/docs/narr/views.rst
@@ -4,23 +4,22 @@ Views
=====
One of the primary jobs of :app:`Pyramid` is to find and invoke a :term:`view
-callable` when a :term:`request` reaches your application. View callables
-are bits of code which do something interesting in response to a request made
-to your application. They are the "meat" of any interesting web application.
+callable` when a :term:`request` reaches your application. View callables are
+bits of code which do something interesting in response to a request made to
+your application. They are the "meat" of any interesting web application.
-.. note::
+.. note::
A :app:`Pyramid` :term:`view callable` is often referred to in
- conversational shorthand as a :term:`view`. In this documentation,
- however, we need to use less ambiguous terminology because there
- are significant differences between view *configuration*, the code
- that implements a view *callable*, and the process of view
- *lookup*.
+ conversational shorthand as a :term:`view`. In this documentation, however,
+ we need to use less ambiguous terminology because there are significant
+ differences between view *configuration*, the code that implements a view
+ *callable*, and the process of view *lookup*.
-This chapter describes how view callables should be defined. We'll have to
-wait until a following chapter (entitled :ref:`view_config_chapter`) to find
-out how we actually tell :app:`Pyramid` to wire up view callables to
-particular URL patterns and other request circumstances.
+This chapter describes how view callables should be defined. We'll have to wait
+until a following chapter (entitled :ref:`view_config_chapter`) to find out how
+we actually tell :app:`Pyramid` to wire up view callables to particular URL
+patterns and other request circumstances.
.. index::
single: view callables
@@ -28,21 +27,21 @@ particular URL patterns and other request circumstances.
View Callables
--------------
-View callables are, at the risk of sounding obvious, callable Python
-objects. Specifically, view callables can be functions, classes, or instances
-that implement a ``__call__`` method (making the instance callable).
+View callables are, at the risk of sounding obvious, callable Python objects.
+Specifically, view callables can be functions, classes, or instances that
+implement a ``__call__`` method (making the instance callable).
-View callables must, at a minimum, accept a single argument named
-``request``. This argument represents a :app:`Pyramid` :term:`Request`
-object. A request object represents a :term:`WSGI` environment provided to
-:app:`Pyramid` by the upstream WSGI server. As you might expect, the request
-object contains everything your application needs to know about the specific
-HTTP request being made.
+View callables must, at a minimum, accept a single argument named ``request``.
+This argument represents a :app:`Pyramid` :term:`Request` object. A request
+object represents a :term:`WSGI` environment provided to :app:`Pyramid` by the
+upstream WSGI server. As you might expect, the request object contains
+everything your application needs to know about the specific HTTP request being
+made.
A view callable's ultimate responsibility is to create a :app:`Pyramid`
-:term:`Response` object. This can be done by creating a :term:`Response`
-object in the view callable code and returning it directly or by raising
-special kinds of exceptions from within the body of a view callable.
+:term:`Response` object. This can be done by creating a :term:`Response` object
+in the view callable code and returning it directly or by raising special kinds
+of exceptions from within the body of a view callable.
.. index::
single: view calling convention
@@ -76,17 +75,17 @@ Defining a View Callable as a Class
-----------------------------------
A view callable may also be represented by a Python class instead of a
-function. When a view callable is a class, the calling semantics are
-slightly different than when it is a function or another non-class callable.
-When a view callable is a class, the class' ``__init__`` method is called with a
+function. When a view callable is a class, the calling semantics are slightly
+different than when it is a function or another non-class callable. When a view
+callable is a class, the class's ``__init__`` method is called with a
``request`` parameter. As a result, an instance of the class is created.
Subsequently, that instance's ``__call__`` method is invoked with no
-parameters. Views defined as classes must have the following traits:
+parameters. Views defined as classes must have the following traits.
-- an ``__init__`` method that accepts a ``request`` argument.
+- an ``__init__`` method that accepts a ``request`` argument
-- a ``__call__`` (or other) method that accepts no parameters and which
- returns a response.
+- a ``__call__`` (or other) method that accepts no parameters and which returns
+ a response
For example:
@@ -106,12 +105,12 @@ The request object passed to ``__init__`` is the same type of request object
described in :ref:`function_as_view`.
If you'd like to use a different attribute than ``__call__`` to represent the
-method expected to return a response, you can use an ``attr`` value as part
-of the configuration for the view. See :ref:`view_configuration_parameters`.
-The same view callable class can be used in different view configuration
-statements with different ``attr`` values, each pointing at a different
-method of the class if you'd like the class to represent a collection of
-related view callables.
+method expected to return a response, you can use an ``attr`` value as part of
+the configuration for the view. See :ref:`view_configuration_parameters`. The
+same view callable class can be used in different view configuration statements
+with different ``attr`` values, each pointing at a different method of the
+class if you'd like the class to represent a collection of related view
+callables.
.. index::
single: view response
@@ -135,11 +134,11 @@ implements the :term:`Response` interface is to return a
def view(request):
return Response('OK')
-:app:`Pyramid` provides a range of different "exception" classes which
-inherit from :class:`pyramid.response.Response`. For example, an instance of
-the class :class:`pyramid.httpexceptions.HTTPFound` is also a valid response
-object because it inherits from :class:`~pyramid.response.Response`. For
-examples, see :ref:`http_exceptions` and :ref:`http_redirect`.
+:app:`Pyramid` provides a range of different "exception" classes which inherit
+from :class:`pyramid.response.Response`. For example, an instance of the class
+:class:`pyramid.httpexceptions.HTTPFound` is also a valid response object
+because it inherits from :class:`~pyramid.response.Response`. For examples,
+see :ref:`http_exceptions` and :ref:`http_redirect`.
.. note::
@@ -155,7 +154,7 @@ examples, see :ref:`http_exceptions` and :ref:`http_redirect`.
.. _special_exceptions_in_callables:
-Using Special Exceptions In View Callables
+Using Special Exceptions in View Callables
------------------------------------------
Usually when a Python exception is raised within a view callable,
@@ -176,14 +175,14 @@ exception` objects.
HTTP Exceptions
~~~~~~~~~~~~~~~
-All :mod:`pyramid.httpexceptions` classes which are documented
-as inheriting from the :class:`pyramid.httpexceptions.HTTPException` are
-:term:`http exception` objects. Instances of an HTTP exception object may
-either be *returned* or *raised* from within view code. In either case
-(return or raise) the instance will be used as the view's response.
+All :mod:`pyramid.httpexceptions` classes which are documented as inheriting
+from the :class:`pyramid.httpexceptions.HTTPException` are :term:`http
+exception` objects. Instances of an HTTP exception object may either be
+*returned* or *raised* from within view code. In either case (return or raise)
+the instance will be used as the view's response.
-For example, the :class:`pyramid.httpexceptions.HTTPUnauthorized` exception
-can be raised. This will cause a response to be generated with a ``401
+For example, the :class:`pyramid.httpexceptions.HTTPUnauthorized` exception can
+be raised. This will cause a response to be generated with a ``401
Unauthorized`` status:
.. code-block:: python
@@ -194,8 +193,8 @@ Unauthorized`` status:
def aview(request):
raise HTTPUnauthorized()
-An HTTP exception, instead of being raised, can alternately be *returned*
-(HTTP exceptions are also valid response objects):
+An HTTP exception, instead of being raised, can alternately be *returned* (HTTP
+exceptions are also valid response objects):
.. code-block:: python
:linenos:
@@ -207,11 +206,11 @@ An HTTP exception, instead of being raised, can alternately be *returned*
A shortcut for creating an HTTP exception is the
:func:`pyramid.httpexceptions.exception_response` function. This function
-accepts an HTTP status code and returns the corresponding HTTP exception.
-For example, instead of importing and constructing a
-:class:`~pyramid.httpexceptions.HTTPUnauthorized` response object, you can
-use the :func:`~pyramid.httpexceptions.exception_response` function to
-construct and return the same object.
+accepts an HTTP status code and returns the corresponding HTTP exception. For
+example, instead of importing and constructing a
+:class:`~pyramid.httpexceptions.HTTPUnauthorized` response object, you can use
+the :func:`~pyramid.httpexceptions.exception_response` function to construct
+and return the same object.
.. code-block:: python
:linenos:
@@ -223,8 +222,8 @@ construct and return the same object.
This is the case because ``401`` is the HTTP status code for "HTTP
Unauthorized". Therefore, ``raise exception_response(401)`` is functionally
-equivalent to ``raise HTTPUnauthorized()``. Documentation which maps each
-HTTP response code to its purpose and its associated HTTP exception object is
+equivalent to ``raise HTTPUnauthorized()``. Documentation which maps each HTTP
+response code to its purpose and its associated HTTP exception object is
provided within :mod:`pyramid.httpexceptions`.
.. versionadded:: 1.1
@@ -233,22 +232,22 @@ provided within :mod:`pyramid.httpexceptions`.
How Pyramid Uses HTTP Exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-HTTP exceptions are meant to be used directly by application
-developers. However, Pyramid itself will raise two HTTP exceptions at
-various points during normal operations:
+HTTP exceptions are meant to be used directly by application developers.
+However, Pyramid itself will raise two HTTP exceptions at various points during
+normal operations.
-* :exc:`~pyramid.httpexceptions.HTTPNotFound`
- gets raised when a view to service a request is not found.
-* :exc:`~pyramid.httpexceptions.HTTPForbidden`
- gets raised when authorization was forbidden by a security policy.
+* :exc:`~pyramid.httpexceptions.HTTPNotFound` gets raised when a view to
+ service a request is not found.
+* :exc:`~pyramid.httpexceptions.HTTPForbidden` gets raised when authorization
+ was forbidden by a security policy.
If :exc:`~pyramid.httpexceptions.HTTPNotFound` is raised by Pyramid itself or
-within view code, the result of the :term:`Not Found View` will be returned
-to the user agent which performed the request.
+within view code, the result of the :term:`Not Found View` will be returned to
+the user agent which performed the request.
If :exc:`~pyramid.httpexceptions.HTTPForbidden` is raised by Pyramid itself
-within view code, the result of the :term:`Forbidden View` will be returned
-to the user agent which performed the request.
+within view code, the result of the :term:`Forbidden View` will be returned to
+the user agent which performed the request.
.. index::
single: exception views
@@ -266,7 +265,7 @@ responses.
To register a view that should be called whenever a particular exception is
raised from within :app:`Pyramid` view code, use the exception class (or one of
its superclasses) as the :term:`context` of a view configuration which points
-at a view callable you'd like to generate a response for.
+at a view callable for which you'd like to generate a response.
For example, given the following exception class in a module named
``helloworld.exceptions``:
@@ -300,8 +299,8 @@ view callable will be invoked whenever a
view code. The same exception raised by a custom root factory, a custom
traverser, or a custom view or route predicate is also caught and hooked.
-Other normal view predicates can also be used in combination with an
-exception view registration:
+Other normal view predicates can also be used in combination with an exception
+view registration:
.. code-block:: python
:linenos:
@@ -315,24 +314,24 @@ exception view registration:
response.status_int = 500
return response
-The above exception view names the ``route_name`` of ``home``, meaning that
-it will only be called when the route matched has a name of ``home``. You
-can therefore have more than one exception view for any given exception in
-the system: the "most specific" one will be called when the set of request
+The above exception view names the ``route_name`` of ``home``, meaning that it
+will only be called when the route matched has a name of ``home``. You can
+therefore have more than one exception view for any given exception in the
+system: the "most specific" one will be called when the set of request
circumstances match the view registration.
-The only view predicate that cannot be used successfully when creating
-an exception view configuration is ``name``. The name used to look up
-an exception view is always the empty string. Views registered as
-exception views which have a name will be ignored.
+The only view predicate that cannot be used successfully when creating an
+exception view configuration is ``name``. The name used to look up an
+exception view is always the empty string. Views registered as exception views
+which have a name will be ignored.
.. note::
- Normal (i.e., non-exception) views registered against a context resource
- type which inherits from :exc:`Exception` will work normally. When an
- exception view configuration is processed, *two* views are registered. One
- as a "normal" view, the other as an "exception" view. This means that you
- can use an exception as ``context`` for a normal view.
+ Normal (i.e., non-exception) views registered against a context resource type
+ which inherits from :exc:`Exception` will work normally. When an exception
+ view configuration is processed, *two* views are registered. One as a
+ "normal" view, the other as an "exception" view. This means that you can use
+ an exception as ``context`` for a normal view.
Exception views can be configured with any view registration mechanism:
``@view_config`` decorator or imperative ``add_view`` styles.
@@ -340,9 +339,9 @@ Exception views can be configured with any view registration mechanism:
.. note::
Pyramid's :term:`exception view` handling logic is implemented as a tween
- factory function: :func:`pyramid.tweens.excview_tween_factory`. If
- Pyramid exception view handling is desired, and tween factories are
- specified via the ``pyramid.tweens`` configuration setting, the
+ factory function: :func:`pyramid.tweens.excview_tween_factory`. If Pyramid
+ exception view handling is desired, and tween factories are specified via
+ the ``pyramid.tweens`` configuration setting, the
:func:`pyramid.tweens.excview_tween_factory` function must be added to the
``pyramid.tweens`` configuration setting list explicitly. If it is not
present, Pyramid will not perform exception view handling.
@@ -358,11 +357,9 @@ Using a View Callable to do an HTTP Redirect
You can issue an HTTP redirect by using the
:class:`pyramid.httpexceptions.HTTPFound` class. Raising or returning an
-instance of this class will cause the client to receive a "302 Found"
-response.
+instance of this class will cause the client to receive a "302 Found" response.
-To do so, you can *return* a :class:`pyramid.httpexceptions.HTTPFound`
-instance.
+To do so, you can *return* a :class:`pyramid.httpexceptions.HTTPFound` instance.
.. code-block:: python
:linenos:
@@ -400,32 +397,31 @@ submission data using the :term:`WebOb` API, see :ref:`webob_chapter` and
`"Query and POST variables" within the WebOb documentation
<http://docs.webob.org/en/latest/reference.html#query-post-variables>`_.
:app:`Pyramid` defers to WebOb for its request and response implementations,
-and handling form submission data is a property of the request
-implementation. Understanding WebOb's request API is the key to
-understanding how to process form submission data.
-
-There are some defaults that you need to be aware of when trying to handle
-form submission data in a :app:`Pyramid` view. Having high-order (i.e.,
-non-ASCII) characters in data contained within form submissions is
-exceedingly common, and the UTF-8 encoding is the most common encoding used
-on the web for character data. Since Unicode values are much saner than
-working with and storing bytestrings, :app:`Pyramid` configures the
-:term:`WebOb` request machinery to attempt to decode form submission values
-into Unicode from UTF-8 implicitly. This implicit decoding happens when view
-code obtains form field values via the ``request.params``, ``request.GET``,
-or ``request.POST`` APIs (see :ref:`request_module` for details about these
-APIs).
+and handling form submission data is a property of the request implementation.
+Understanding WebOb's request API is the key to understanding how to process
+form submission data.
+
+There are some defaults that you need to be aware of when trying to handle form
+submission data in a :app:`Pyramid` view. Having high-order (i.e., non-ASCII)
+characters in data contained within form submissions is exceedingly common, and
+the UTF-8 encoding is the most common encoding used on the web for character
+data. Since Unicode values are much saner than working with and storing
+bytestrings, :app:`Pyramid` configures the :term:`WebOb` request machinery to
+attempt to decode form submission values into Unicode from UTF-8 implicitly.
+This implicit decoding happens when view code obtains form field values via the
+``request.params``, ``request.GET``, or ``request.POST`` APIs (see
+:ref:`request_module` for details about these APIs).
.. note::
- Many people find the difference between Unicode and UTF-8 confusing.
- Unicode is a standard for representing text that supports most of the
- world's writing systems. However, there are many ways that Unicode data
- can be encoded into bytes for transit and storage. UTF-8 is a specific
- encoding for Unicode, that is backwards-compatible with ASCII. This makes
- UTF-8 very convenient for encoding data where a large subset of that data
- is ASCII characters, which is largely true on the web. UTF-8 is also the
- standard character encoding for URLs.
+ Many people find the difference between Unicode and UTF-8 confusing. Unicode
+ is a standard for representing text that supports most of the world's
+ writing systems. However, there are many ways that Unicode data can be
+ encoded into bytes for transit and storage. UTF-8 is a specific encoding for
+ Unicode that is backwards-compatible with ASCII. This makes UTF-8 very
+ convenient for encoding data where a large subset of that data is ASCII
+ characters, which is largely true on the web. UTF-8 is also the standard
+ character encoding for URLs.
As an example, let's assume that the following form page is served up to a
browser client, and its ``action`` points at some :app:`Pyramid` view code:
@@ -450,8 +446,8 @@ browser client, and its ``action`` points at some :app:`Pyramid` view code:
The ``myview`` view code in the :app:`Pyramid` application *must* expect that
the values returned by ``request.params`` will be of type ``unicode``, as
-opposed to type ``str``. The following will work to accept a form post from
-the above form:
+opposed to type ``str``. The following will work to accept a form post from the
+above form:
.. code-block:: python
:linenos:
@@ -479,31 +475,31 @@ encoding of UTF-8. This can be done via a response that has a
with a ``meta http-equiv`` tag that implies that the charset is UTF-8 within
the HTML ``head`` of the page containing the form. This must be done
explicitly because all known browser clients assume that they should encode
-form data in the same character set implied by ``Content-Type`` value of the
-response containing the form when subsequently submitting that form. There is
-no other generally accepted way to tell browser clients which charset to use
-to encode form data. If you do not specify an encoding explicitly, the
-browser client will choose to encode form data in its default character set
-before submitting it, which may not be UTF-8 as the server expects. If a
-request containing form data encoded in a non-UTF8 charset is handled by your
-view code, eventually the request code accessed within your view will throw
-an error when it can't decode some high-order character encoded in another
-character set within form data, e.g., when ``request.params['somename']`` is
-accessed.
+form data in the same character set implied by the ``Content-Type`` value of
+the response containing the form when subsequently submitting that form. There
+is no other generally accepted way to tell browser clients which charset to use
+to encode form data. If you do not specify an encoding explicitly, the browser
+client will choose to encode form data in its default character set before
+submitting it, which may not be UTF-8 as the server expects. If a request
+containing form data encoded in a non-UTF-8 ``charset`` is handled by your view
+code, eventually the request code accessed within your view will throw an error
+when it can't decode some high-order character encoded in another character set
+within form data, e.g., when ``request.params['somename']`` is accessed.
If you are using the :class:`~pyramid.response.Response` class to generate a
response, or if you use the ``render_template_*`` templating APIs, the UTF-8
-charset is set automatically as the default via the ``Content-Type`` header.
-If you return a ``Content-Type`` header without an explicit charset, a
-request will add a ``;charset=utf-8`` trailer to the ``Content-Type`` header
-value for you, for response content types that are textual
-(e.g. ``text/html``, ``application/xml``, etc) as it is rendered. If you are
-using your own response object, you will need to ensure you do this yourself.
+``charset`` is set automatically as the default via the ``Content-Type``
+header. If you return a ``Content-Type`` header without an explicit
+``charset``, a request will add a ``;charset=utf-8`` trailer to the
+``Content-Type`` header value for you for response content types that are
+textual (e.g., ``text/html`` or ``application/xml``) as it is rendered. If you
+are using your own response object, you will need to ensure you do this
+yourself.
-.. note:: Only the *values* of request params obtained via
- ``request.params``, ``request.GET`` or ``request.POST`` are decoded
- to Unicode objects implicitly in the :app:`Pyramid` default
- configuration. The keys are still (byte) strings.
+.. note:: Only the *values* of request params obtained via ``request.params``,
+ ``request.GET`` or ``request.POST`` are decoded to Unicode objects
+ implicitly in the :app:`Pyramid` default configuration. The keys are still
+ (byte) strings.
.. index::
@@ -514,7 +510,7 @@ using your own response object, you will need to ensure you do this yourself.
Alternate View Callable Argument/Calling Conventions
----------------------------------------------------
-Usually, view callables are defined to accept only a single argument:
+Usually view callables are defined to accept only a single argument:
``request``. However, view callables may alternately be defined as classes,
functions, or any callable that accept *two* positional arguments: a
:term:`context` resource as the first argument and a :term:`request` as the
@@ -532,8 +528,7 @@ request
The following types work as view callables in this style:
-#. Functions that accept two arguments: ``context``, and ``request``,
- e.g.:
+#. Functions that accept two arguments: ``context`` and ``request``, e.g.:
.. code-block:: python
:linenos:
@@ -543,8 +538,8 @@ The following types work as view callables in this style:
def view(context, request):
return Response('OK')
-#. Classes that have an ``__init__`` method that accepts ``context,
- request`` and a ``__call__`` method which accepts no arguments, e.g.:
+#. Classes that have an ``__init__`` method that accepts ``context, request``,
+ and a ``__call__`` method which accepts no arguments, e.g.:
.. code-block:: python
:linenos:
@@ -559,8 +554,8 @@ The following types work as view callables in this style:
def __call__(self):
return Response('OK')
-#. Arbitrary callables that have a ``__call__`` method that accepts
- ``context, request``, e.g.:
+#. Arbitrary callables that have a ``__call__`` method that accepts ``context,
+ request``, e.g.:
.. code-block:: python
:linenos:
@@ -597,7 +592,6 @@ Pylons-1.0-Style "Controller" Dispatch
--------------------------------------
A package named :term:`pyramid_handlers` (available from PyPI) provides an
-analogue of :term:`Pylons` -style "controllers", which are a special kind of
-view class which provides more automation when your application uses
-:term:`URL dispatch` solely.
-
+analogue of :term:`Pylons`-style "controllers", which are a special kind of
+view class which provides more automation when your application uses :term:`URL
+dispatch` solely.
diff --git a/docs/tutorials/wiki2/basiclayout.rst b/docs/tutorials/wiki2/basiclayout.rst
index 08132e8cd..80ae4b34e 100644
--- a/docs/tutorials/wiki2/basiclayout.rst
+++ b/docs/tutorials/wiki2/basiclayout.rst
@@ -204,7 +204,7 @@ Let's examine this in detail. First, we need some imports to support later code:
Next we set up a SQLAlchemy ``DBSession`` object:
.. literalinclude:: src/basiclayout/tutorial/models.py
- :lines: 16
+ :lines: 17
:language: py
``scoped_session`` and ``sessionmaker`` are standard SQLAlchemy helpers.