Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge of andrew-docs branch.

  • Loading branch information...
commit 9ec2d646eb23b88e4ef8119b0b46240081953daf 1 parent 96d6306
Chris McDonough authored
Showing with 2,720 additions and 2,102 deletions.
  1. +19 −5 TODO.txt
  2. +64 −0 docs/authorintro.rst
  3. +4 −0 docs/build_book
  4. +72 −29 docs/conf.py
  5. +22 −17 docs/copyright.rst
  6. +15 −0 docs/glossary.rst
  7. +1 −1  docs/index.rst
  8. +2 −3 docs/latexindex.rst
  9. +234 −715 docs/narr/configuration.rst
  10. +6 −6 docs/narr/environment.rst
  11. +49 −43 docs/narr/events.rst
  12. +34 −32 docs/narr/extending.rst
  13. +767 −0 docs/narr/firstapp.rst
  14. +99 −106 docs/narr/hybrid.rst
  15. +70 −37 docs/narr/install.rst
  16. +106 −151 docs/narr/introduction.rst
  17. +79 −28 docs/narr/models.rst
  18. +236 −150 docs/narr/project.rst
  19. +44 −42 docs/narr/router.rst
  20. +0 −202 docs/narr/scanning.rst
  21. +136 −83 docs/narr/security.rst
  22. +14 −23 docs/narr/startup.rst
  23. +266 −174 docs/narr/templates.rst
  24. +23 −21 docs/narr/unittesting.rst
  25. +51 −9 docs/narr/urldispatch.rst
  26. +19 −24 docs/narr/urlmapping.rst
  27. +29 −21 docs/narr/vhosting.rst
  28. +208 −145 docs/narr/views.rst
  29. +1 −1  docs/narr/webob.rst
  30. +0 −17 docs/thanks.rst
  31. +3 −0  docs/tutorials/bfgwiki/authorization.rst
  32. +3 −0  docs/tutorials/bfgwiki/basiclayout.rst
  33. +3 −0  docs/tutorials/bfgwiki/definingmodels.rst
  34. +7 −5 docs/tutorials/bfgwiki/definingviews.rst
  35. +3 −1 docs/tutorials/bfgwiki/index.rst
  36. +4 −0 docs/tutorials/bfgwiki2/authorization.rst
  37. +3 −0  docs/tutorials/bfgwiki2/basiclayout.rst
  38. +3 −0  docs/tutorials/bfgwiki2/definingmodels.rst
  39. +7 −5 docs/tutorials/bfgwiki2/definingviews.rst
  40. +3 −1 docs/tutorials/bfgwiki2/index.rst
  41. +0 −4 docs/whatsnew-1.2.rst
  42. +11 −1 repoze/bfg/events.py
View
24 TODO.txt
@@ -1,10 +1,24 @@
-- Audit the rest of the docs for "view configuration" and "route
- configuration" references, etc.
-
-- Basic WSGI documentation (pipeline / app / server).
-
- Decide on ``unhook_zca`` argument to ``tearDown``.
- Get rid of ITraverser hook in favor of IViewLookup.
- Named notfound views.
+
+- Review:
+
+ [ ] Traversal
+
+ [ ] URL dispatch
+
+ [ ] Combining Traversal and URL Dispatch
+
+ [ ] Views
+
+- Review tutorials.
+
+- Review index.
+
+- Review API docs.
+
+- Basic WSGI documentation (pipeline / app / server).
+
View
64 docs/authorintro.rst
@@ -0,0 +1,64 @@
+Author Introduction
+===================
+
+This is the "author introduction", wherein, I, the author put stuff
+that goes nowhere else.
+
+The Genesis of :mod:`repoze.bfg`
+--------------------------------
+
+I wrote :mod:`repoze.bfg` after many years of writing applications
+using :term:`Zope`. Zope provided me with a lot of mileage: it wasn't
+until almost a decade of succesfully creating applications using Zope
+that I decided to write a different web framework. Although
+:mod:`repoze.bfg` takes inspiration from a variety of web frameworks,
+it owes more of its design ethos to Zope than any other.
+
+The "Repoze" brand existed before :mod:`repoze.bfg`. One of the first
+packages developed as part of the Repoze brand was a package named
+:mod:`repoze.zope2`. This was a package that allowed Zope 2
+applications to run under a :term:`WSGI` server without modification.
+Zope 2 did not have reasonable WSGI support at the time.
+
+During the development of the :mod:`repoze.zope2` package, I found
+that replicating the Zope 2 "publisher" -- the machinery that maps
+URLs to code -- was time-consuming and fiddly. Zope 2 had evolved
+over many years, and emulating all of its edge cases was extremely
+difficult. I finished the :mod:`repoze.zope2` package, and it
+emulates the normal Zope 2 publisher pretty well. But during its
+development, it became clear that Zope 2 had simply begun to exceed my
+tolerance for complexity, and I began to look around for simpler
+options.
+
+I considered the using Zope 3 application server machinery, but it
+turned out that it had become more indirect than the Zope 2 machinery
+it aimed to replace, which didn't fulfill the goal of simplification.
+I also considered using Django and Pylons, but neither of those
+frameworks offer much along the axes of traversal, contextual
+declarative security, or application extensibility; these were
+features I had become accustomed to as a Zope developer.
+
+I decided that in the long term, creating a simpler, legacy-free
+framework that retained features I had become accustomed to when
+developing Zope applications was a more reasonable idea than
+continuing to use any Zope publisher or living with the limitations
+and unfamiliarities of a different framework. The result is what is
+now :mod:`repoze.bfg`.
+
+Thanks
+------
+
+This book is dedicated to my grandmother, Dorothy Phillips.
+
+Thanks to the following people for providing expertise, resources, and
+software. Without the help of these folks, neither this book nor the
+software which it details would exist: Paul Everitt, Tres Seaver,
+Andrew Sawyers, Malthe Borch, Carlos de la Guardia, Georg Brandl,
+Simon Oram of Electrosoup, Ian Bicking of the Open Planning Project,
+Jim Fulton of Zope Corporation, Tom Moroz of the Open Society
+Institute, and Todd Koym of Environmental Health Sciences.
+
+Special thanks to Guido van Rossum and Tim Peters for Python.
+
+Special thanks also to Tricia for putting up with me.
+
View
4 docs/build_book
@@ -0,0 +1,4 @@
+#!/bin/sh
+BOOK=1 make clean latex
+cd .build/latex
+make all
View
101 docs/conf.py
@@ -211,24 +211,29 @@
\pagestyle{fancy}
+% header and footer styles
\renewcommand{\chaptermark}[1]%
-{\markboth{\MakeUppercase{\thechapter.\ #1}}{}}
+ {\markboth{\MakeUppercase{\thechapter.\ #1}}{}
+ }
\renewcommand{\sectionmark}[1]%
-{\markright{\MakeUppercase{\thesection.\ #1}}}
-\renewcommand{\headrulewidth}{0.5pt}
+ {\markright{\MakeUppercase{\thesection.\ #1}}
+ }
+
+% defaults for fancy style
+\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}
\fancyhf{}
\fancyfoot[C]{\thepage}
-\fancyhead[RO]{\rightmark}
-\fancyhead[LE]{\leftmark}
+% plain style
\fancypagestyle{plain}{
- \fancyhf{} % empty header and footer
\renewcommand{\headrulewidth}{0pt} % ho header line
- \renewcommand{\footrulewidth}{0pt}% not footer line
- \fancyfoot[C]{\thepage}% like fancy style
+ \renewcommand{\footrulewidth}{0pt}% no footer line
+ \fancyhf{} % empty header and footer
+ \fancyfoot[C]{\thepage}
}
+% title page styles
\makeatletter
\def\@subtitle{\relax}
\newcommand{\subtitle}[1]{\gdef\@subtitle{#1}}
@@ -242,7 +247,7 @@
}
\makeatother
-% Redefine these colors to your liking in the preamble.
+% Redefine link and title colors
\definecolor{TitleColor}{rgb}{0,0,0}
\definecolor{InnerLinkColor}{rgb}{0.208,0.374,0.486}
\definecolor{OuterLinkColor}{rgb}{0.216,0.439,0.388}
@@ -252,29 +257,13 @@
\definecolor{VerbatimBorderColor}{rgb}{1,1,1}
\makeatletter
-% Notices / Admonitions
-%
-\newcommand{\py@veryheavybox}{
- \setlength{\fboxrule}{2pt}
- \setlength{\fboxsep}{7pt}
- \setlength{\py@noticelength}{\linewidth}
- \addtolength{\py@noticelength}{-2\fboxsep}
- \addtolength{\py@noticelength}{-2\fboxrule}
- \setlength{\shadowsize}{3pt}
- \Sbox
- \minipage{\py@noticelength}
-}
-\newcommand{\py@endveryheavybox}{
- \endminipage
- \endSbox
- \fbox{\TheSbox}
-}
\renewcommand{\py@noticestart@warning}{\py@heavybox}
\renewcommand{\py@noticeend@warning}{\py@endheavybox}
\renewcommand{\py@noticestart@note}{\py@heavybox}
\renewcommand{\py@noticeend@note}{\py@endheavybox}
\makeatother
+% icons in note and warning boxes
\usepackage{ifthen}
% Keep a copy of the original notice environment
\let\origbeginnotice\notice
@@ -291,7 +280,20 @@
\origendnotice% equivalent to original \end{notice}
}
+% try to prevent code-block boxes from splitting across pages
\sloppy
+\widowpenalty=300
+\clubpenalty=300
+\setlength{\parskip}{3ex plus 2ex minus 2ex}
+
+% suppress page numbers on pages showing part title
+\makeatletter
+\let\sv@endpart\@endpart
+\def\@endpart{\thispagestyle{empty}\sv@endpart}
+\makeatother
+
+% prevent page numbers in TOC (reset to fancy by frontmatter directive)
+\pagestyle{empty}
"""
latex_elements = {
@@ -305,17 +307,58 @@
from docutils import nodes
+# secnumdepth counter reset to 2 causes numbering in related matter;
+# reset to -1 causes chapters to not be numbered, reset to -2 causes
+# parts to not be numbered.
+
+#part -1
+#chapter 0
+#section 1
+#subsection 2
+#subsubsection 3
+#paragraph 4
+#subparagraph 5
+
def frontmatter(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
- return [nodes.raw('', '\\frontmatter\n', format='latex')]
+ return [nodes.raw(
+ '',
+ r"""
+\frontmatter
+% prevent part/chapter/section numbering
+\setcounter{secnumdepth}{-2}
+% suppress headers
+\pagestyle{plain}
+% reset page counter
+\setcounter{page}{1}
+% suppress first toc pagenum
+\addtocontents{toc}{\protect\thispagestyle{empty}}
+""",
+ format='latex')]
def mainmatter(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
- return [nodes.raw('', '\\mainmatter\n', format='latex')]
+ return [nodes.raw(
+ '',
+ r"""
+\mainmatter
+% allow part/chapter/section numbering
+\setcounter{secnumdepth}{2}
+% get headers back
+\pagestyle{fancy}
+\fancyhf{}
+\renewcommand{\headrulewidth}{0.5pt}
+\renewcommand{\footrulewidth}{0pt}
+\fancyfoot[C]{\thepage}
+\fancyhead[RO]{\rightmark}
+\fancyhead[LE]{\leftmark}
+""",
+ format='latex')]
def backmatter(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
- return [nodes.raw('', '\\backmatter\n', format='latex')]
+ return [nodes.raw('', '\\backmatter\n\\setcounter{secnumdepth}{-1}\n',
+ format='latex')]
def setup(app):
app.add_directive('frontmatter', frontmatter, 1, (0, 0, 0))
View
39 docs/copyright.rst
@@ -1,5 +1,5 @@
-Copyright and Trademarks
-========================
+Copyright, Trademarks, and Attributions
+=======================================
*The repoze.bfg Web Application Framework*
@@ -11,7 +11,7 @@ Copyright |copy| 2008-2010, Agendaless Consulting.
ISBN-13: 978-0-615-34537-6
-First publishing: 2010
+First print publishing: 2010
All rights reserved. This material may be copied or distributed only
subject to the terms and conditions set forth in the `Creative Commons
@@ -30,14 +30,24 @@ similar license to this one.
`less restrictive (BSD-like) license
<http://repoze.org/license.html>`_ .
-**Trademarks**
-
All terms mentioned in this book that are known to be trademarks or
service marks have been appropriately capitalized. However, use of a
term in this book should not be regarded as affecting the validity of
any trademark or service mark.
-**Attributions**
+Every effort has been made to make this book as complete and as
+accurate as possible, but no warranty or fitness is implied. The
+information provided is on as "as-is" basis. The author and the
+publisher shall have neither liability nor responsibility to any
+person or entity with respect to any loss or damages arising from the
+information contained in this book. No patent liability is assumed
+with respect to the use of the information contained herein.
+
+Attributions
+------------
+
+Technical Reviewer:
+ Andrew Sawyers
Cover Designer:
`Electrosoup <http://www.electrosoup.co.uk>`_.
@@ -46,17 +56,11 @@ Used with permission:
The :ref:`webob_chapter` chapter is adapted, with permission, from
documentation originally written by Ian Bicking.
-**Warning and Disclaimer**
-
-Every effort has been made to make this book as complete and as
-accurate as possible, but no warranty or fitness is implied. The
-information provided is on as "as-is" basis. The author and the
-publisher shall have neither liability nor responsibility to any
-person or entity with respect to any loss or damages arising from the
-information contained in this book. No patent liability is assumed
-with respect to the use of the information contained herein.
+Foreword:
+ Paul Everitt
-**Contacting The Publisher**
+Contacting The Publisher
+------------------------
Please send documentation licensing inquiries, translation inquiries,
and other business communications to `Agendaless Consulting
@@ -64,7 +68,8 @@ and other business communications to `Agendaless Consulting
technical queries to the `repoze-dev maillist
<http://lists.repoze.org/listinfo/repoze-dev>`_.
-**Source Code**
+Source Code
+-----------
The source code for this book is available within the
:mod:`repoze.bfg` software distribution, always available via
View
15 docs/glossary.rst
@@ -621,3 +621,18 @@ Glossary
Agendaless Consulting
A consulting organization formed by Paul Everitt, Tres Seaver,
and Chris McDonough. See also http://agendaless.com .
+
+ Jython
+ A `Python implementation <http://www.jython.org/>` written for
+ the Java Virtual Machine.
+
+ Python
+ The `programming language <http://python.org>` in which
+ :mod:`repoze.bfg` is written.
+
+ CPython
+ The C implementation of the Python language. This is the
+ reference implementation that most people refer to as simply
+ "Python"; :term:`Jython`, Google's App Engine, and `PyPy
+ <http://codespeak.net/pypy/dist/pypy/doc/>`_ are examples of
+ non-C based Python implementations.
View
2  docs/index.rst
@@ -45,7 +45,7 @@ Narrative documentation in chapter form explaining how to use
narr/introduction
narr/install
narr/configuration
- narr/scanning
+ narr/firstapp
narr/project
narr/startup
narr/urlmapping
View
5 docs/latexindex.rst
@@ -13,9 +13,9 @@ Front Matter
:maxdepth: 1
copyright.rst
- thanks.rst
conventions.rst
foreword.rst
+ authorintro.rst
.. mainmatter::
@@ -28,7 +28,7 @@ Narrative Documentation
narr/introduction
narr/install
narr/configuration
- narr/scanning
+ narr/firstapp
narr/project
narr/urlmapping
narr/views
@@ -36,7 +36,6 @@ Narrative Documentation
narr/templates
narr/models
narr/security
- narr/hybrid
narr/vhosting
narr/events
narr/environment
View
949 docs/narr/configuration.rst
@@ -1,48 +1,19 @@
-.. index::
- single: frameworks vs. libraries
- single: framework
-
.. _configuration_narr:
-Creating Your First :mod:`repoze.bfg` Application
-=================================================
-
-Most of the logic in a web application is completely
-application-specific. For example, the content of a web page served
-by one web application might be a representation of the contents of an
-accounting ledger, while the content of of a web page served by
-another might be a listing of songs. These applications probably
-won't serve the same set of customers. However, both the
-ledger-serving and song-serving applications can be written using
-:mod:`repoze.bfg`, because :mod:`repoze.bfg` is a very general
-*framework* which can be used to create all kinds of web applications.
-As a framework, the primary job of :mod:`repoze.bfg` is to make it
-easier for a developer to create an arbitrary web application.
-
-.. 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.
+.. index::
+ single: application configuration
+
+Application Configuration
+=========================
Each deployment of an application written using :mod:`repoze.bfg`
implies a specific *configuration* of the framework itself. For
-example, a song-serving application might plug code into the framework
-that manages songs, while the ledger- serving application might plug
-in code that manages accounting information. :mod:`repoze.bfg` refers
-to the way in which code is plugged in to it for a specific
-application as "configuration".
+example, an application which serves up MP3s for user consumption
+might plug code into the framework that manages songs, while an
+application that application might plug in code that manages
+accounting information. :mod:`repoze.bfg` refers to the way in which
+code is plugged in to it for a specific application as
+"configuration".
Most people understand "configuration" as coarse knobs that inform the
high-level operation of a specific application deployment. For
@@ -55,24 +26,25 @@ code into the :mod:`repoze.bfg` framework, you are "configuring"
:mod:`repoze.bfg` for the purpose of creating a particular application
deployment.
-There are a number of different mechanisms you may use to configure
+There are two different mechanisms you may use to configure
:mod:`repoze.bfg` to create an application: *imperative* configuration
and *declarative* configuration. We'll examine both modes in the
sections which follow.
.. index::
- pair: imperative; helloworld
+ pair: imperative; configuration
-.. _helloworld_imperative:
+.. _imperative_configuration:
-Hello World, Configured Imperatively
-------------------------------------
+Imperative Configuration
+------------------------
-Experienced Python programmers might find that "imperative"
-configuration is easiest to use. This is the configuration mode in
-which a developer cedes the least amount of control to the framework;
-it's "imperative" because you express the configuration directly in
-Python code.
+Experienced Python programmers might find that performing
+configuration "imperatively" fits their brain best. This is the
+configuration mode in which a developer cedes the least amount of
+control to the framework; it's "imperative" because you express the
+configuration directly in Python code, and you have the full power of
+Python at your disposal as you perform configuration statements.
Here's one of the simplest :mod:`repoze.bfg` applications, configured
imperatively:
@@ -87,491 +59,45 @@ imperatively:
def hello_world(request):
return Response('Hello world!')
- def goodbye_world(request):
- return Response('Goodbye world!')
-
if __name__ == '__main__':
config = Configurator()
config.begin()
config.add_view(hello_world)
- config.add_view(goodbye_world, name='goodbye')
config.end()
app = config.make_wsgi_app()
serve(app)
-When this code is inserted into a Python script named
-``helloworld.py`` and executed by a Python interpreter which has the
-:mod:`repoze.bfg` software installed, an HTTP server is started on
-port 8080. When port 8080 is visited by a user agent on the root URL
-(``/``), the server will simply serve up the text "Hello world!" with
-the HTTP response values ``200 OK`` as a response code and a
-``Content-Type`` header value of ``text/plain``. But for reasons
-we'll better understand shortly, when visited by a user agent on the
-URL ``/goodbye``, the server will serve up "Goodbye world!".
-
-Let's examine this program piece-by-piece.
-
-Imports
-~~~~~~~
-
-The above script defines the following set of imports:
-
-.. code-block:: python
- :linenos:
-
- from webob import Response
- from paste.httpserver import serve
- from repoze.bfg.configuration import Configurator
-
-:mod:`repoze.bfg` uses the :term:`WebOb` library as the basis for its
-:term:`request` and :term:`response` objects. The script uses the
-:class:`webob.Response` class later in the script to create a
-:term:`response` object.
-
-Like many other Python web frameworks, :mod:`repoze.bfg` uses the
-:term:`WSGI` protocol to connect an application and a web server
-together. The :mod:`paste.httpserver` server is used in this example
-as a WSGI server for convenience, as ``Paste`` is a dependency of
-:mod:`repoze.bfg` itself. However, :mod:`repoze.bfg` applications can
-be served by any WSGI server.
-
-The script also imports the ``Configurator`` class from the
-``repoze.bfg.configuration`` module. This class is used to configure
-:mod:`repoze.bfg` for a particular application. An instance of this
-class provides methods which help configure various parts of
-:mod:`repoze.bfg` for a given application deployment.
-
-View Declaration
-~~~~~~~~~~~~~~~~
-
-The above script, beneath its set of imports, defines two functions:
-one named ``hello_world`` and one named ``goodbye_world``.
-
-.. code-block:: python
- :linenos:
-
- def hello_world(request):
- return Response('Hello world!')
-
- def goodbye_world(request):
- return Response('Goodbye world!')
-
-Each function accepts a single argument (``request``) and returns an
-instance of the :class:`webob.Response` class. In the ``hello_world``
-function, the string ``'Hello world!'`` is passed to the ``Response``
-constructor as the *body* of the response. In the ``goodbye_world``
-function, the string ``'Goodbye world!'`` is passed.
-
-Each of these functions is known as a :term:`view callable`. View
-callables in a "real" :mod:`repoze.bfg` application are often
-functions which accept a :term:`request` and return a
-:term:`response`. A view callable 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 called with a :term:`request` object, which is a
-representation of an HTTP request sent by a remote user agent. 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 and sent
-back to the requesting user agent.
-
-The ``hello_world`` view callable defined by the script does nothing
-but return a response with the body ``Hello world!``; the
-``goodbye_world`` view callable returns a response with the body
-``Goodbye world!``.
-
-.. index::
- pair: traversal; introduction
-
-.. _traversal_intro:
-
-An Introduction to Traversal
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-If you've run the code listed in :ref`helloworld_imperative` already,
-you've unwittingly configured :mod:`repoze.bfg` to serve an
-application that relies on :term:`traversal`. A full explanation of
-how :mod:`repoze.bfg` locates "the right" :term:`view callable` for a
-given request requires some explanation of :term:`traversal`.
-
-Traversal is part of a mechanism used by :mod:`repoze.bfg` to map the
-URL of some request to a particular :term:`view callable`. It is not
-the only mechanism made available by :mod:`repoze.bfg` that allows the
-mapping a URL to a view callable. Another distinct mode known as
-:term:`URL dispatch` can alternately be used to find a view callable
-based on a URL. However, our sample application uses only
-:term:`traversal`.
-
-In :mod:`repoze.bfg` terms, :term:`traversal` is the act of walking
-over an object graph starting from a :term:`root` object in order to
-find a :term:`context` object and a :term:`view name`. Once a context
-and a view name are found, these two bits of information, plus other
-information from the request are used to look up a :term:`view
-callable`. :mod:`repoze.bfg` bothers to do traversal only because the
-information returned from traversal allows a view callable to be
-found.
-
-The individual path segments of the "path info" portion of a URL (the
-data following the hostname and port number, but before any query
-string elements or fragments, for example the ``/a/b/c`` portion of
-the URL ``http://example.com/a/b/c?foo=1``) are used as "steps" during
-traversal.
-
-.. note:: A useful analogy of how :mod:`repoze.bfg` :term:`traversal`
- works is available within the chapter section entitled
- :ref:`traversal_behavior`.
-
-The results of a :term:`traversal` include a :term:`context` and a
-:term:`view name`. The :term:`view name` is the *first* URL path
-segment in the set of path segments "left over" in the results of
-:term:`traversal`. This will either be the empty string (``''``) or a
-non-empty string (one of the path segment strings). The empty string
-represents the :term:`default view` of a context object.
-
-The :term:`default view` is found when all path elements in the URL
-are exhausted before :term:`traversal` returns a :term:`context`
-object, causing the :term:`view name` to be ``''`` (the empty string).
-When no path segments are "left over" after traversal, the
-:term:`default view` for the context found is invoked.
-
-If traversal returns a non-empty :term:`view name`, it means that
-traversal "ran out" of nodes in the graph before it finished
-exhausting all the path segments implied by the path info of the URL:
-no segments are "left over". In this case, because the :term:`view
-name` is non-empty, a *non-default* view callable will be invoked.
-
-The combination of the :term:`context` object and the :term:`view
-name` (and, in more complex configurations, other :term:`predicate`
-values) are used to find "the right" :term:`view callable`, which will
-be invoked after traversal.
-
-The object graph of our hello world application is very simple:
-there's exactly one object in our graph; the default :term:`root`
-object.
-
-Relating Traversal to the Hello World Application
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Our application's :term:`root` object is the *default* root object
-used when one isn't otherwise specified in application configuration.
-This root object does not have a ``__getitem__`` method, thus it has
-no children. Although in a more complex system there can be many
-contexts which URLs resolve to in our application, effectively there
-is only ever one context: the root object.
-
-We have only a single default view registered (the registration for
-the ``hello_world`` view callable). Due to this set of circumstances,
-you can consider the sole possible URL that will resolve to a
-:term:`default view` in this application the root URL ``'/'``. It is
-the only URL that will resolve to the :term:`view name` of ``''`` (the
-empty string).
-
-We have only a single view registered for the :term:`view name`
-``goodbye`` (the registration for the ``goodbye_world`` view
-callable). Due to this set of circumstances, you can consider the
-sole possible URL that will resolve to the ``goodbye_world`` in this
-application the URL ``'/goodbye'`` because it is the only URL that
-will resolve to the :term:`view name` of ``goodbye``.
-
-.. index::
- pair: imperative; configuration
- single: Configurator
-
-.. _helloworld_imperative_appconfig:
-
-Application Configuration
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
-In the above script, the following code, representing the
-*configuration* of an application which uses the previously defined
-imports and function definitions is placed within the confines of an
-``if`` statement:
-
-.. code-block:: python
- :linenos:
-
- if __name__ == '__main__':
- config = Configurator()
- config.begin()
- config.add_view(hello_world)
- config.add_view(goodbye_world, name='goodbye')
- config.end()
- app = config.make_wsgi_app()
- simple_server.make_server('', 8080, app).serve_forever()
-
-Let's break this down this piece-by-piece.
-
-Configurator Construction
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
-.. code-block:: python
- :linenos:
-
- if __name__ == '__main__':
- config = Configurator()
-
-The ``if __name__ == '__main__':`` line above represents a Python
-idiom: the code inside this if clause is not invoked unless the script
-is run directly from the command line via, for example, ``python
-helloworld.py`` where the file named ``helloworld.py`` contains the
-entire script body. ``helloworld.py`` in this case is a Python
-*module*. Using the ``if`` clause is necessary (or at least "best
-practice") because code in any Python module may be imported by
-another Python module. By using this idiom, the script is indicating
-that it does not want the code within the ``if`` statement to execute
-if this module is imported; 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:`repoze.bfg.configuration.Configurator` class. The resulting
-``config`` object represents an API which the script uses to configure
-this particular :mod:`repoze.bfg` application.
-
-.. note::
-
- An instance of the :class:`repoze.bfg.configuration.Configurator`
- class is a *wrapper* object which mutates an :term:`application
- registry` as its methods are called. An application registry
- represents the configuration state of a :mod:`repoze.bfg`
- application. The ``Configurator`` is not itself an
- :term:`application registry`, it is a mechanism used to configure
- an application registry. The underlying application registry
- object being configured by a ``Configurator`` is available as its
- ``registry`` attribute.
-
-Beginning Configuration
-~~~~~~~~~~~~~~~~~~~~~~~
-
-.. ignore-next-block
-.. code-block:: python
-
- config.begin()
-
-The :meth:`repoze.bfg.configuration.Configurator.begin` method tells
-the the system that application configuration has begun. In
-particular, this causes the :term:`application registry` associated
-with this configurator to become the "current" application registry,
-meaning that code which attempts to use the application registry
-:term:`thread local` will obtain the registry associated with the
-configurator. This is an explicit step because it's sometimes
-convenient to use a configurator without causing the registry
-associated with the configurator to become "current".
-
-Adding Configuration
-~~~~~~~~~~~~~~~~~~~~
-
-.. ignore-next-block
-.. code-block:: python
- :linenos:
-
- config.add_view(hello_world)
- config.add_view(goodbye_world, name='goodbye')
-
-Each of these lines calls the
-:meth:`repoze.bfg.configuration.Configurator.add_view` method. The
-``add_view`` method of a configurator registers a :term:`view
-configuration` within the :term:`application registry`. A :term:`view
-configuration` represents a :term:`view callable` which must be
-invoked when a set of circumstances related to the :term:`request` is
-true. This "set of circumstances" is provided as one or more keyword
-arguments to the ``add_view`` method, otherwise known as
-:term:`predicate` arguments.
-
-The line ``config.add_view(hello_world)`` registers the
-``hello_world`` function as a view callable. The ``add_view`` method
-of a Configurator must be called with a view callable object as its
-first argument, so the first argument passed is ``hello_world``
-function we'd like to use as a :term:`view callable`. However, this
-line calls ``add_view`` with a single default :term:`predicate`
-argument, the ``name`` predicate with a value of ``''``, meaning that
-we'd like :mod:`repoze.bfg` to invoke the ``hello_world`` view
-callable for any request for the :term:`default view` of an object.
-
-Our ``hello_world`` :term:`view callable` returns a Response instance
-with a body of ``Hello world!`` in the configuration implied by this
-script. It is configured as a :term:`default view`. Therefore, a
-user agent contacting a server running this application will receive
-the greeting ``Hello world!`` when any :term:`default view` is
-invoked.
-
-.. sidebar:: View Dispatch and Ordering
-
- When :term:`traversal` is used, :mod:`repoze.bfg` chooses the most
- specific view callable based *only* on view :term:`predicate`
- applicability. This is unlike :term:`URL dispatch`, another
- dispatch mode of :mod:`repoze.bfg` (and other frameworks, like
- :term:`Pylons` and :term:`Django`) which first uses an ordered
- routing lookup to resolve the request to a view callable by running
- it through a relatively-ordered series of URL path matches. We're
- not really concerned about the finer details of :term:`URL
- dispatch` right now. It's just useful to use for demonstrative
- purposes: the ordering of calls to
- :meth:`repoze.bfg.configuration.Configurator.add_view`` is never
- very important. We can register ``goodbye_world`` first and
- ``hello_world`` second; :mod:`repoze.bfg` will still give us the
- most specific callable when a request is dispatched to it.
-
-The line ``config.add_view(goodbye_world, name='goodbye')`` registers
-the ``goodbye_world`` function as a view callable. The line calls
-``add_view`` with the view callable as the first required positional
-argument, and a :term:`predicate` keyword argument ``name`` with the
-value ``'goodbye'``. This :term:`view configuration` implies that a
-request with a :term:`view name` of ``goodbye`` should cause the
-``goodbye_world`` view callable to be invoked. For the purposes of
-this discussion, the :term:`view name` can be considered the first
-non-empty path segment in the URL: in particular, this view
-configuration will match when the URL is ``/goodbye``.
-
-Our ``goodbye_world`` :term:`view callable` returns a Response
-instance with a body of ``Goodbye world!`` in the configuration
-implied by this script. It is configured as with a :term:`view name`
-predicate of ``goodbye``. Therefore, a user agent contacting a server
-running this application will receive the greeting ``Goodbye world!``
-when the path info part of the request is ``/goodbye``.
-
-Each invocation of the ``add_view`` method implies a :term:`view
-configuration` registration. Each :term:`predicate` provided as a
-keyword argument to the ``add_view`` method narrows the set of
-circumstances which would cause the view configuration's callable to
-be invoked. In general, a greater number of predicates supplied along
-with a view configuration will more strictly limit the applicability
-of its associated view callable. When :mod:`repoze.bfg` processes a
-request, however, the view callable with the *most specific* view
-configuration (the view configuration that matches the largest number
-of predicates) is always invoked.
-
-Earlier we explained that the server would return ``Hello world!`` if
-you visited the *root* (``/``) URL. However, actually, because the
-view configuration registration for the ``hello_world`` view callable
-has no :term:`predicate` arguments, the ``hello_world`` view callable
-is applicable for the :term:`default view` of any :term:`context`
-resulting from a request. This isn't all that interesting in this
-application, because we always only have *one* potential context (the
-root object): it is the only object in the graph.
-
-We've also registered a view configuration for another circumstance:
-the ``goodbye_world`` view callable has a ``name`` predicate of
-``goodbye``, meaning that it will match for requests that have the
-:term:`view name` ``goodbye`` unlike the ``hello_world`` view
-configuration registration, which will only match the default view
-(view name ``''``) of a request. Because :mod:`repoze.bfg` chooses
-the best view configuration for any request, the ``goodbye_world``
-view callable will be used when the URL contains path information that
-ends with ``/goodbye``.
-
-Ending Configuration
-~~~~~~~~~~~~~~~~~~~~
-
-.. ignore-next-block
-.. code-block:: python
-
- config.end()
-
-The :meth:`repoze.bfg.configuration.Configurator.end` method tells the
-the system that application configuration has ended. It is the
-inverse of :meth:`repoze.bfg.configuration.Configurator.begin`. In
-particular, this causes the :term:`application registry` associated
-with this configurator to no longer be the "current" application
-registry, meaning that code which attempts to use the application
-registry :term:`thread local` will no longer obtain the registry
-associated with the configurator.
-
-.. index::
- single: make_wsgi_app
- pair: WSGI; application
- triple: WSGI; application; creation
-
-WSGI Application Creation
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
-.. ignore-next-block
-.. code-block:: python
-
- app = config.make_wsgi_app()
-
-After configuring views and ending configuration, the script creates a
-WSGI *application* via the
-:meth:`repoze.bfg.configuration.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 set 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.
-
-The :mod:`repoze.bfg` application object, in particular, is an
-instance of the :class:`repoze.bfg.router.Router` class. It has a
-reference to the :term:`application registry` which resulted from
-method calls to the configurator used to configure it. The Router
-consults the registry to obey the policy choices made by a single
-application. These policy choices were informed by method calls to
-the ``Configurator`` made earlier; in our case, the only policy
-choices made were implied by two calls to the ``add_view`` method,
-telling our application that it should effectively serve up the
-``hello_world`` view callable to any user agent when it visits the
-root URL, and the ``goodbye_world`` view callable to any user agent
-when it visits the URL with the path info ``/goodbye``.
-
-WSGI Application Serving
-~~~~~~~~~~~~~~~~~~~~~~~~
-
-.. ignore-next-block
-.. code-block:: python
-
- serve(app)
-
-Finally, we actually serve the application to requestors by starting
-up a WSGI server. We happen to use the :func:`paste.httpserver.serve`
-WSGI server runner, using the default TCP port of 8080, and we pass it
-the ``app`` object (an instance of the
-:class:`repoze.bfg.router.Router` class) as the application we wish to
-serve. This causes the server to start listening on the TCP port. It
-will serve requests forever, or at least until we stop it by killing
-the process which runs it.
-
-Conclusion
-~~~~~~~~~~
-
-Our hello world application is one of the simplest possible
-:mod:`repoze.bfg` applications, configured "imperatively". We can see
-a good deal of what's going on "under the hood" when we configure a
-:mod:`repoze.bfg` application imperatively. However, another mode of
-configuration exists named *declarative* configuration.
+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.begin()``,
+``config.add_view(...)``, and ``config.end()``. 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::
- pair: helloworld; declarative
- single: helloworld
+ pair: declarative; configuration
-.. _helloworld_declarative:
+.. _declarative_configuration:
-Hello World, Configured Declaratively
--------------------------------------
+Declarative Configuration
+-------------------------
-:mod:`repoze.bfg` can be configured for the same "hello world"
-application "declaratively", if so desired. Declarative configuration
-relies on *declarations* made external to the code in a configuration
-file format named :term:`ZCML` (Zope Configuration Markup Language),
-an XML dialect.
+A :mod:`repoze.bfg` application can be alternatively be configured
+"declaratively", if so desired. Declarative configuration relies on
+*declarations* made external to the code in a configuration file
+format named :term:`ZCML` (Zope Configuration Markup Language), an XML
+dialect.
Declarative configuration mode is the configuration mode in which
developers cede the most amount of control to the framework itself.
Because application developers cede more control to the framework, it
-is also harder to understand than purely imperative configuration.
-However, using declarative configuration has a number of benefits, the
-primary benefit being that applications configured declaratively can
-be *overridden* and *extended* by third parties without requiring the
-third party to change application code.
-
-.. note::
+is also sometimes harder to understand than purely imperative
+configuration.
- See :ref:`extending_chapter` for a discussion of extending and
- overriding :mod:`repoze.bfg` applications.
-
-Unlike the simplest :mod:`repoze.bfg` application configured
-imperatively, the simplest :mod:`repoze.bfg` application, configured
-declaratively requires not one, but two files: a Python file and a
-:term:`ZCML` file.
+A :mod:`repoze.bfg` application configured declaratively requires not
+one, but two files: a Python file and a :term:`ZCML` file.
In a file named ``helloworld.py``:
@@ -585,9 +111,6 @@ In a file named ``helloworld.py``:
def hello_world(request):
return Response('Hello world!')
- def goodbye_world(request):
- return Response('Goodbye world!')
-
if __name__ == '__main__':
config = Configurator()
config.begin()
@@ -610,19 +133,16 @@ previously created ``helloworld.py``:
view="helloworld.hello_world"
/>
- <view
- name="goodbye"
- view="helloworld.goodbye_world"
- />
-
</configure>
This pair of files forms an application functionally equivalent to the
-application we created earlier. Let's examine the differences between
-the code described in :ref:`helloworld_imperative` and the code above.
+application we created earlier in :ref:`imperative_configuration`.
+
+Let's examine the differences between the code listing in
+:ref:`imperative_configuration` and the code above.
-In :ref:`helloworld_imperative_appconfig`, we had the following lines
-within the ``if __name__ == '__main__'`` section of ``helloworld.py``:
+In :ref:`imperative_configuration`, we had the following lines within
+the ``if __name__ == '__main__'`` section of ``helloworld.py``:
.. code-block:: python
:linenos:
@@ -631,16 +151,14 @@ within the ``if __name__ == '__main__'`` section of ``helloworld.py``:
config = Configurator()
config.begin()
config.add_view(hello_world)
- config.add_view(goodbye_world, name='goodbye')
config.end()
app = config.make_wsgi_app()
- simple_server.make_server('', 8080, app).serve_forever()
+ serve(app)
-In our "declarative" code, we've added a call to the
-:meth:`repoze.bfg.configuration.Configurator.load_zcml` method with
-the value ``configure.zcml``, and we've removed the lines which read
-``config.add_view(hello_world)`` and ``config.add_view(goodbye_world,
-name='goodbye')``, so that it now reads as:
+In our "declarative" code, we've removed the call to ``add_view`` and
+replaced it with a call to the
+:meth:`repoze.bfg.configuration.Configurator.load_zcml` method so that
+it now reads as:
.. code-block:: python
:linenos:
@@ -651,14 +169,14 @@ name='goodbye')``, so that it now reads as:
config.load_zcml('configure.zcml')
config.end()
app = config.make_wsgi_app()
- simple_server.make_server('', 8080, app).serve_forever()
+ serve(app)
Everything else is much the same.
The ``config.load_zcml('configure.zcml')`` line tells the configurator
-to load configuration declarations from the ``configure.zcml`` file
-which sits next to ``helloworld.py``. Let's take a look at the
-``configure.zcml`` file now:
+to load configuration declarations from the file named
+``configure.zcml`` which sits next to ``helloworld.py`` on the
+filesystem. Let's take a look at that ``configure.zcml`` file again:
.. code-block:: xml
:linenos:
@@ -671,166 +189,45 @@ which sits next to ``helloworld.py``. Let's take a look at the
view="helloworld.hello_world"
/>
- <view
- name="goodbye"
- view="helloworld.goodbye_world"
- />
-
</configure>
-The ``<configure>`` Tag
-~~~~~~~~~~~~~~~~~~~~~~~
-
-The ``configure.zcml`` ZCML file contains this bit of XML:
-
-.. code-block:: xml
- :linenos:
-
- <configure xmlns="http://namespaces.repoze.org/bfg">
-
- <!-- other directives -->
-
- </configure>
-
-Because :term:`ZCML` is XML, and because XML requires a single root
-tag for each document, every ZCML file used by :mod:`repoze.bfg` must
-contain a ``configure`` container directive, which acts as the root
-XML tag. It is a "container" directive because its only job is to
-contain other directives.
-
-See also :ref:`configure_directive` and :ref:`word_on_xml_namespaces`.
-
-The ``<include>`` Tag
-~~~~~~~~~~~~~~~~~~~~~
-
-The ``configure.zcml`` ZCML file contains this bit of XML within the
-``<configure>`` root tag:
-
-.. code-block:: xml
-
- <include package="repoze.bfg.includes" />
-
-This singleton (self-closing) tag instructs ZCML to load a ZCML file
-from the Python package with the :term:`dotted Python name`
-:mod:`repoze.bfg.includes`, as specified by its ``package`` attribute.
-This particular ``<include>`` declaration is required because it
-actually allows subsequent declaration tags (such as ``<view>``, which
-we'll see shortly) to be recognized. The ``<include>`` tag
-effectively just includes another ZCML file; this causes its
-declarations to be executed. In this case, we want to load the
-declarations from the file named ``configure.zcml`` within the
-:mod:`repoze.bfg.includes` Python package. We know we want to load
-the ``configure.zcml`` from this package because ``configure.zcml`` is
-the default value for another attribute of the ``<include>`` tag named
-``file``. We could have spelled the include tag more verbosely, but
-equivalently as:
-
-.. code-block:: xml
- :linenos:
-
- <include package="repoze.bfg.includes"
- file="configure.zcml"/>
+Note that this file contains some XML, and that the XML contains a
+``<view>`` :term:`configuration declaration` tag that references a
+:term:`dotted Python name`. This dotted name refers to the
+``hello_world`` function that lives in our ``helloword`` Python
+module.
-The ``<include>`` tag that includes the ZCML statements implied by the
-``configure.zcml`` file from the Python package named
-:mod:`repoze.bfg.includes` is basically required to come before any
-other named declaration in an application's ``configure.zcml``. If it
-is not included, subsequent declaration tags will fail to be
-recognized, and the configuration system will generate a traceback.
-However, the ``<include package="repoze.bfg.includes"/>`` tag needs to
-exist only in a "top-level" ZCML file, it needn't also exist in ZCML
-files *included by* a top-level ZCML file.
+This ``<view>`` declaration tag performs the same function as the
+``add_view`` method that was employed within
+:ref:`imperative_configuration`. In fact, the ``<view>`` tag is
+effectively a "macro" which calls the
+:meth:`repoze.bfg.configuration.Configurator.add_view` method on your
+behalf.
-See also :ref:`include_directive`.
-
-The ``<view>`` Tag
-~~~~~~~~~~~~~~~~~~
-
-The ``configure.zcml`` ZCML file contains these bits of XML *after* the
-``<include>`` tag, but *within* the ``<configure>`` root tag:
-
-.. code-block:: xml
- :linenos:
-
- <view
- view="helloworld.hello_world"
- />
-
- <view
- name="goodbye"
- view="helloworld.goodbye_world"
- />
-
-These ``<view>`` declaration tags direct :mod:`repoze.bfg` to create
-two :term:`view configuration` registrations. The first ``<view>``
-tag has an attribute (the attribute is also named ``view``), which
-points at a :term:`dotted Python name`, referencing the
-``hello_world`` function defined within the ``helloworld`` package.
-The second ``<view>`` tag has a ``view`` attribute which points at a
-:term:`dotted Python name`, referencing the ``goodbye_world`` function
-defined within the ``helloworld`` package. The second ``<view>`` tag
-also has an attribute called ``name`` with a value of ``goodbye``.
-
-These effect of the ``<view>`` tag declarations we've put into our
-``configure.zcml`` is functionally equivalent to the effect of lines
-we've already seen in an imperatively-configured application. We're
-just spelling things differently, using XML instead of Python.
-
-In our previously defined application, in which we added view
-configurations imperatively, we saw this code:
-
-.. ignore-next-block
-.. code-block:: python
- :linenos:
-
- config.add_view(hello_world)
- config.add_view(goodbye_world, name='goodbye')
-
-Each ``<view>`` declaration tag encountered in a ZCML file effectively
-invokes the :meth:`repoze.bfg.configuration.Configurator.add_view`
-method on the behalf of the developer. Various attributes can be
-specified on the ``<view>`` tag which influence the :term:`view
-configuration` it creates.
-
-Since the relative ordering of calls to
-:meth:`repoze.bfg.configuration.Configurator.add_view` doesn't matter
-(see the sidebar entitled *View Dispatch and Ordering*), the relative
-order of ``<view>`` tags in ZCML doesn't matter either. The following
-ZCML orderings are completely equivalent:
-
-.. topic:: Hello Before Goodbye
-
- .. code-block:: xml
- :linenos:
-
- <view
- view="helloworld.hello_world"
- />
-
- <view
- name="goodbye"
- view="helloworld.goodbye_world"
- />
+The ``<view>`` tag is an example of a :mod:`repoze.bfg` declaration
+tag. Other such tags include ``<route>``, ``<scan>``, ``<notfound>``,
+``<forbidden>``, and others. Each of these tags is effectively a
+"macro" which calls methods of a
+:class:`repoze.bfg.configuration.Configurator` object on your behalf.
-.. topic:: Goodbye Before Hello
+Essentially, using a :term:`ZCML` file and loading it from the
+filesystem allows us to put our configuration statements within this
+XML file rather as declarations, rather than representing them as
+method calls to a :term:`Configurator` object. Otherwise, declarative
+and imperative configuration are functionally equivalent.
- .. code-block:: xml
- :linenos:
+Using declarative configuration has a number of benefits, the primary
+benefit being that applications configured declaratively can be
+*overridden* and *extended* by third parties without requiring the
+third party to change application code.
- <view
- name="goodbye"
- view="helloworld.goodbye_world"
- />
+.. note::
- <view
- view="helloworld.hello_world"
- />
+ See :ref:`extending_chapter` for a discussion of extending and
+ overriding :mod:`repoze.bfg` applications.
-The ``<view>`` tag is an example of a :mod:`repoze.bfg` declaration
-tag. Other such tags include ``<route>``, ``<scan>``, ``<notfound>``,
-``<forbidden>``, and others. Each of these tags is effectively a
-"macro" which calls methods on the
-:class:`repoze.bfg.configuration.Configurator` object on your behalf.
+If you want to build a framework or an extensible application, using
+ZCML is a good idea.
.. index::
pair: ZCML; conflict detection
@@ -838,8 +235,8 @@ tag. Other such tags include ``<route>``, ``<scan>``, ``<notfound>``,
ZCML Conflict Detection
~~~~~~~~~~~~~~~~~~~~~~~
-An additional feature of ZCML is *conflict detection*. If you define
-two declaration tags within the same ZCML file which logically
+A minor additional feature of ZCML is *conflict detection*. If you
+define two declaration tags within the same ZCML file which logically
"collide", an exception will be raised, and the application will not
start. For example, the following ZCML file has two conflicting
``<view>`` tags:
@@ -862,33 +259,155 @@ start. For example, the following ZCML file has two conflicting
</configure>
If you try to use this ZCML file as the source of ZCML for an
-application, a :data:`repoze.bfg.exceptions.ConfigurationError` will
-be raised when you attempt to start the application with information
-about which tags might have conflicted.
+application, an error will be raised when you attempt to start the
+application. This error will contain information about which tags
+might have conflicted.
+
+.. index::
+ single: bfg_view
+ pair: ZCML directive; view
+ single: configuration decorations
+ pair: code; scanning
+
+.. _decorations_and_code_scanning:
+
+Configuration Decorations and Code Scanning
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+An alternate mode of declarative configuration lends more *locality of
+reference* to a :term:`configuration declaration`. It's sometimes
+painful to have all configuration done in ZCML, or even in imperative
+code, because you may need to have two files open at once; the file
+that represents the configuration, and the file that contains the
+implementation objects (such as :term:`view callable` functions) that
+the configuration references. To avoid this, :mod:`repoze.bfg` 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:
-Conclusions
------------
+ from repoze.bfg.view import bfg_view
+ from webob import Response
-.. sidebar:: Which Configuration Mode Should I Use?
+ @bfg_view(name='hello', request_method='GET')
+ def hello(request):
+ return Response('Hello')
+
+The :class:`repoze.bfg.view.bfg_view` decorator above adds an
+attribute to the ``hello`` function, making it available for a
+:term:`scan` to find it later.
+
+The mere existence of configuration decoration doesn't cause any
+configuration registration to be made. Before they have any effect on
+the configuration of a :mod:`repoze.bfg` application, a configuration
+decoration within application code must be found through a process
+known as *scanning*.
+
+:mod:`repoze.bfg` is willing to :term:`scan` a module or a package and
+its subpackages for decorations when the
+:meth:`repoze.bfg.configuration.Configurator.scan` method is invoked:
+scanning implies searching for configuration declarations in a package
+and its subpackages. For example:
+
+.. topic:: Imperatively Starting A Scan
+
+ .. code-block:: python
+ :linenos:
+
+ from paste.httpserver import serve
+ from repoze.bfg.view import bfg_view
+ from webob import Response
+
+ @bfg_view()
+ def hello(request):
+ return Response('Hello')
+
+ if __name__ == '__main__':
+ from repoze.bfg.configuration import Configurator
+ config = Configurator()
+ config.begin()
+ config.scan()
+ config.end()
+ app = config.make_wsgi_app()
+ serve(app)
+
+:term:`ZCML` can also invoke a :term:`scan` via its ``<scan>``
+directive. If a ZCML file is processed that contains a scan
+directive, the package the ZCML file points to is scanned.
+
+.. topic:: Declaratively Starting a Scan
+
+ .. code-block:: python
+ :linenos:
+
+ # helloworld.py
+
+ from paste.httpserver import serve
+ from repoze.bfg.view import bfg_view
+ from webob import Response
+
+ @bfg_view()
+ def hello(request):
+ return Response('Hello')
+
+ if __name__ == '__main__':
+ from repoze.bfg.configuration import Configurator
+ config = Configurator()
+ config.begin()
+ config.load_zcml('configure.zcml')
+ config.end()
+ app = config.make_wsgi_app()
+ serve(app)
+
+ .. code-block:: xml
+ :linenos:
+
+ <configure xmlns="http://namespaces.repoze.org">
+
+ <!-- configure.zcml -->
+
+ <include package="repoze.bfg.includes"/>
+ <scan package="."/>
+
+ </configure>
+
+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 :class:`repoze.bfg.view.bfg_view` 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 behalf of the developer: these calls represent
+the intent of the configuration decoration.
+
+In the example above, this is best represented as the scanner
+translating the arguments to :class:`repoze.bfg.view.bfg_view` into a
+call to the :meth:`repoze.bfg.configuration.Configurator.add_view`
+method, effectively:
- We recommend declarative configuration (:term:`ZCML`), because it's
- the more traditional form of configuration used by Zope-based
- systems, it can be overridden and extended by third party deployers,
- and there are more examples for it "in the wild". However,
- imperative mode configuration can be simpler to understand.
+.. ignore-next-block
+.. code-block:: python
-:mod:`repoze.bfg` allows an application to perform configuration tasks
-either imperatively or declaratively. You can choose the mode that
-best fits your brain as necessary.
+ config.add_view(hello)
-For more information about the API of a ``Configurator`` object, see
-:class:`repoze.bfg.configuration.Configurator` . The equivalent ZCML
-declaration tags are introduced in narrative documentation chapters as
-necessary.
+Which Mode Should I Use?
+------------------------
-For more information about :term:`traversal`, see
-:ref:`traversal_chapter`.
+A combination of imperative configuration, declarative configuration
+via ZCML and scanning can be used to configure any application. They
+are not mutually exclusive.
-For more information about :term:`view configuration`, see
-:ref:`views_chapter`.
+The :mod:`repoze.bfg` authors often recommend using mostly declarative
+configuration, because it's the more traditional form of configuration
+used in :mod:`repoze.bfg` applications, it can be overridden and
+extended by third party deployers, and there are more examples for it
+"in the wild".
+However, imperative mode configuration can be simpler to understand,
+and the framework is not "opinionated" about the choice. This book
+presents examples in both styles, mostly interchangeably. You can
+choose the mode that best fits your brain as necessary.
View
12 docs/narr/environment.rst
@@ -197,10 +197,10 @@ changing the content of an overridden resource directory for templates
without restarting the server after every change. Subsequent requests
for the same template file may return different filenames based on the
current state of overridden resource directories. Setting
-``reload_resources`` to ``True`` effects performance *dramatically*
-(slowing things down by an order of magnitude for each template
-rendering) but it's convenient when moving files around in overridden
-resource directories. ``reload_resources`` makes the system *very
-slow* when templates are in use. Never set ``reload_resources`` to
-``True`` on a production system.
+``reload_resources`` to ``True`` effects performance *dramatically*,
+slowing things down by an order of magnitude for each template
+rendering. However, it's convenient to enable when moving files
+around in overridden resource directories. ``reload_resources`` makes
+the system *very slow* when templates are in use. Never set
+``reload_resources`` to ``True`` on a production system.
View
92 docs/narr/events.rst
@@ -13,11 +13,10 @@ Using Events
An *event* is an object broadcast by the :mod:`repoze.bfg` framework
at interesting points during the lifetime of an application. You
-don't need to use, know about, or care about events in order to create
-most :mod:`repoze.bfg` applications, but they can be useful when you
-want to perform slightly advanced operations. For example,
-subscribing to an event can allow you to "skin" a site slightly
-differently based on the hostname used to reach the site.
+don't need to use events in order to create most :mod:`repoze.bfg`
+applications, but they can be useful when you want to perform slightly
+advanced operations. For example, subscribing to an event can allow
+you to run some code as the result of every new request.
Events in :mod:`repoze.bfg` are always broadcast by the framework.
However, they only become useful when you register a *subscriber*. A
@@ -34,8 +33,10 @@ when it's called.
The mere existence of a subscriber function, however, is not
sufficient to arrange for it to be called. To arrange for the
-subscriber to be called, you'll need to change your :term:`application
-registry` by either of the following methods:
+subscriber to be called, you'll need to use the
+:meth:`repoze.bfg.configurator.Configurator.add_subscriber` method to
+register the subscriber imperatively, or you'll need to use ZCML for
+the same purpose:
.. topic:: Configuring an Event Listener Imperatively
@@ -51,6 +52,9 @@ registry` by either of the following methods:
from subscribers import mysubscriber
+ # "config" below is assumed to be an instance of a
+ # repoze.bfg.configuration.Configurator object
+
config.add_subscriber(mysubscriber, INewRequest)
The first argument to
@@ -73,7 +77,9 @@ registry` by either of the following methods:
handler=".subscribers.mysubscriber"
/>
-Each of the above examples implies that every time the
+ See also :ref:`subscriber_directive`.
+
+Either of the above registration examples implies that every time the
:mod:`repoze.bfg` framework emits an event object that supplies an
:class:`repoze.bfg.interfaces.INewRequest` interface, the
``mysubscriber`` function will be called with an *event* object.
@@ -83,8 +89,18 @@ As you can see, a subscription is made in terms of an
be an object that possesses an interface. The interface itself
provides documentation of what attributes of the event are available.
-For example, if you create event listener functions in a
-``subscribers.py`` file in your application like so:
+The return value of a subscriber function is ignored. Subscribers to
+the same event type are not guaranteed to be called in any particular
+order relative to each another.
+
+All the concrete :mod:`repoze.bfg` event types are documented in the
+:ref:`events_module` API documentation.
+
+An Example
+----------
+
+If you create event listener functions in a ``subscribers.py`` file in
+your application like so:
.. code-block:: python
:linenos:
@@ -96,8 +112,8 @@ For example, if you create event listener functions in a
print 'response', event.response
You may configure these functions to be called at the appropriate
-times by adding the following to your application's ``configure.zcml``
-file:
+times by adding the following ZCML to your application's
+``configure.zcml`` file:
.. code-block:: xml
:linenos:
@@ -112,10 +128,9 @@ file:
handler=".subscribers.handle_new_response"
/>
-See also :ref:`subscriber_directive`.
-
-The :meth:`repoze.bfg.configuration.Configurator.add_subscriber`
-method can be used to perform the same job:
+If you're not using ZCML, the
+:meth:`repoze.bfg.configuration.Configurator.add_subscriber` method
+can alternately be used to perform the same job:
.. ignore-next-block
.. code-block:: python
@@ -127,36 +142,27 @@ method can be used to perform the same job:
from subscribers import handle_new_request
from subscribers import handle_new_response
+ # "config" below is assumed to be an instance of a
+ # repoze.bfg.configuration.Configurator object
+
config.add_subscriber(handle_new_request, INewRequest)
config.add_subscriber(handle_new_response, INewResponse)
-This causes the functions as to be registered as event subscribers
-within the :term:`application registry` . Under this configuration,
-when the application is run, each time a new request or response is
-detected, a message will be printed to the console.
-
-.. sidebar:: The ``INewResponse`` Event vs. Middleware
-
- Postprocessing a response is usually better handled in a WSGI
- :term:`middleware` component than in subscriber code that is called
- by a :class:`repoze.bfg.interfaces.INewResponse` event. The
- :class:`repoze.bfg.interfaces.INewResponse` event exists almost
- purely for symmetry with the
- :class:`repoze.bfg.interfaces.INewRequest` event.
-
-We know that :class:`repoze.bfg.interfaces.INewRequest` events have a
-``request`` attribute, which is a :term:`WebOb` request, because the
-interface defined at :class:`repoze.bfg.interfaces.INewRequest` says
-it must. Likewise, we know that
-:class:`repoze.bfg.interfaces.INewResponse` events have a ``response``
-attribute, which is a response object constructed by your application,
-because the interface defined at
-:class:`repoze.bfg.interfaces.INewResponse` says it must.
+Either mechanism causes the functions in ``subscribers.py`` to be
+registered as event subscribers. Under this configuration, when the
+application is run, each time a new request or response is detected, a
+message will be printed to the console.
-The return value of a subscriber function is ignored. Subscribers to
-the same event type are not guaranteed to be called in any particular
-order relative to one another.
+Each of our subscriber functions accepts an ``event`` object and
+prints an attribute of the event object. This begs the question: how
+can we know which attributes a particular event has?
-All other concrete event types are documented in the
-:ref:`events_module` API documentation.
+We know that :class:`repoze.bfg.interfaces.INewRequest` event objects
+have a ``request`` attribute, which is a :term:`request` object,
+because the interface defined at
+:class:`repoze.bfg.interfaces.INewRequest` says it must. Likewise, we
+know that :class:`repoze.bfg.interfaces.INewResponse` events have a
+``response`` attribute, which is a response object constructed by your
+application, because the interface defined at
+:class:`repoze.bfg.interfaces.INewResponse` says it must.
View
66 docs/narr/extending.rst
@@ -4,11 +4,10 @@ Extending An Existing :mod:`repoze.bfg` Application
===================================================
If the developer of a :mod:`repoze.bfg` application has obeyed certain
-constraints while building the application, a third party should be able to
-change the behavior of that application without needing to modify the actual
-source code that makes up the application. The behavior of a
-:mod:`repoze.bfg` application that obeys these constraints can be
-*overridden* or *extended* without modification.
+constraints while building that application, a third party should be
+able to change its behavior without needing to modify its source code.
+The behavior of a :mod:`repoze.bfg` application that obeys certain
+constraints can be *overridden* or *extended* without modification.
.. index::
triple: building; extensible; application
@@ -25,13 +24,13 @@ the a :term:`scan`, and you mustn't configure your :mod:`repoze.bfg`
application *imperatively* by using any code which configures the
application through methods of the :term:`Configurator` (except for
the :meth:`repoze.bfg.configuration.Configurator.load_zcml` method).
-Instead, should must use :term:`ZCML` for the equivalent
+
+Instead, must always use :term:`ZCML` for the equivalent
purposes. :term:`ZCML` declarations that belong to an application can
be "overridden" by integrators as necessary, but decorators and
-imperative code which perform the same tasks cannot.
-
-In general: use only :term:`ZCML` to configure your application if
-you'd like it to be extensible.
+imperative code which perform the same tasks cannot. Use only
+:term:`ZCML` to configure your application if you'd like it to be
+extensible.
Fundamental Plugpoints
~~~~~~~~~~~~~~~~~~~~~~
@@ -50,16 +49,16 @@ and templates.
ZCML Granularity
~~~~~~~~~~~~~~~~
-It's also extremely helpful to third party application "extenders"
-(aka "integrators") if the :term:`ZCML` that composes the
-configuration for an application is broken up into separate files
-which do very specific things. These more specific ZCML files can be
-reintegrated within the application's main ``configure.zcml`` via
-``<include file="otherfile.zcml"/>`` declarations. When ZCML files
-contain sets of specific declarations, an integrator can avoid
-including any ZCML he does not want by including only ZCML files which
-contain the declarations he needs. He is not forced to "accept
-everything" or "use nothing".
+It's extremely helpful to third party application "extenders" (aka
+"integrators") if the :term:`ZCML` that composes the configuration for
+an application is broken up into separate files which do very specific
+things. These more specific ZCML files can be reintegrated within the
+application's main ``configure.zcml`` via ``<include
+file="otherfile.zcml"/>`` declarations. When ZCML files contain sets
+of specific declarations, an integrator can avoid including any ZCML
+he does not want by including only ZCML files which contain the
+declarations he needs. He is not forced to "accept everything" or
+"use nothing".
For example, it's often useful to put all ``<route>`` declarations in
a separate ZCML file, as ``<route>`` statements have a relative
@@ -102,17 +101,19 @@ configuration imperatively, one of two things may be true:
*may* need to change the source code of the original application.
If the only source of trouble is the existence of
- :class:`repoze.bfg.view.bfg_view` decorators, you can just omit the
- ``<scan>`` directive in the application ZCML. This will cause the
- decorators to do nothing. At this point, you will need to convert
- all the configuration done in decorators into equivalent
- :term:`ZCML` and add that ZCML to an a separate Python package as
- described in :ref:`extending_the_application`.
-
- If the source of trouble is configuration done imperatively (perhaps
- in the function called during application startup), you'll need to
- change the code: convert imperative configuration into equivalent
- :term:`ZCML` declarations.
+ :class:`repoze.bfg.view.bfg_view` decorators, you can just prevent a
+ :term:`scan` from happening (by omitting the ``<scan>`` declaration
+ from ZCML or omitting any call to the
+ :meth:`repoze.bfg.configuration.Configurator.scan` method). This
+ will cause the decorators to do nothing. At this point, you will
+ need to convert all the configuration done in decorators into
+ equivalent :term:`ZCML` and add that ZCML to an a separate Python
+ package as described in :ref:`extending_the_application`.
+
+ If the source of trouble is configuration done imperatively in a
+ function called during application startup, you'll need to change
+ the code: convert imperative configuration statements into
+ equivalent :term:`ZCML` declarations.
Once this is done, you should be able to extend or override the
application like any other (see :ref:`extending_the_application`).
@@ -157,7 +158,8 @@ something like this:
- Create an ``overrides.zcml`` file within the new package. The
statements in the ``overrides.zcml`` file will override any ZCML
- statements made within the original application (such as views).
+ statements made within the original application (such as view
+ declarations).
- Create Python files containing views and other overridden elements,
such as templates and static resources as necessary, and wire these
View
767 docs/narr/firstapp.rst
@@ -0,0 +1,767 @@
+.. _configuration_narr:
+
+Creating Your First :mod:`repoze.bfg` Application
+=================================================
+
+We'll walk through the creation of a tiny :mod:`repoze.bfg`
+application in this chapter, and explain in more detail how the
+application works.
+
+.. index::
+ single: helloworld
+
+.. _helloworld_imperative:
+
+Hello World, Goodbye World (Imperative)
+---------------------------------------
+
+Here's one of the simplest :mod:`repoze.bfg` applications, configured
+imperatively:
+
+.. code-block:: python
+ :linenos:
+
+ from webob import Response
+ from paste.httpserver import serve
+ from repoze.bfg.configuration import Configurator
+
+ def hello_world(request):
+ return Response('Hello world!')
+
+ def goodbye_world(request):
+ return Response('Goodbye world!')
+
+ if __name__ == '__main__':
+ config = Configurator()
+ config.begin()
+ config.add_view(hello_world)
+ config.add_view(goodbye_world, name='goodbye')
+ config.end()
+ app = config.make_wsgi_app()
+ serve(app)
+
+When this code is inserted into a Python script named
+``helloworld.py`` and executed by a Python interpreter which has the
+:mod:`repoze.bfg` software installed, an HTTP server is started on
+port 8080. When port 8080 is visited by a user agent on the root URL
+(``/``), the server will simply serve up the text "Hello world!" with
+the HTTP response values ``200 OK`` as a response code and a
+``Content-Type`` header value of ``text/plain``. But for reasons
+we'll better understand shortly, when visited by a user agent on the
+URL ``/goodbye``, the server will serve up "Goodbye world!".
+
+Let's examine this program piece-by-piece.
+
+Imports
+~~~~~~~
+
+The above script defines the following set of imports:
+
+.. code-block:: python
+ :linenos:
+
+ from webob import Response
+ from paste.httpserver import serve
+ from repoze.bfg.configuration import Configurator
+
+:mod:`repoze.bfg` uses the :term:`WebOb` library as the basis for its
+:term:`request` and :term:`response` objects. The script uses the
+:class:`webob.Response` class later in the script to create a
+:term:`response` object.
+
+Like many other Python web frameworks, :mod:`repoze.bfg` uses the
+:term:`WSGI` protocol to connect an application and a web server
+together. The :mod:`paste.httpserver` server is used in this example
+as a WSGI server for convenience, as ``Paste`` is a dependency of
+:mod:`repoze.bfg` itself. However, :mod:`repoze.bfg` applications can
+be served by any WSGI server.
+
+The script also imports the ``Configurator`` class from the
+``repoze.bfg.configuration`` module. This class is used to configure
+:mod:`repoze.bfg` for a particular application. An instance of this
+class provides methods which help configure various parts of
+:mod:`repoze.bfg` for a given application deployment.
+
+View Declaration
+~~~~~~~~~~~~~~~~
+
+The above script, beneath its set of imports, defines two functions:
+one named ``hello_world`` and one named ``goodbye_world``.
+
+.. code-block:: python
+ :linenos:
+
+ def hello_world(request):
+ return Response('Hello world!')
+
+ def goodbye_world(request):
+ return Response('Goodbye world!')
+
+Each function accepts a single argument (``request``) and returns an
+instance of the :class:`webob.Response` class. In the ``hello_world``
+function, the string ``'Hello world!'`` is passed to the ``Response``
+constructor as the *body* of the response. In the ``goodbye_world``
+function, the string ``'Goodbye world!'`` is passed.
+
+Each of these functions is known as a :term:`view callable`. View
+callables in a "real" :mod:`repoze.bfg` application are often
+functions which accept a :term:`request` and return a
+:term:`response`. A view callable 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 called with a :term:`request` object, which is a
+representation of an HTTP request sent by a remote user agent. 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 and sent
+back to the requesting user agent.
+
+The ``hello_world`` view callable defined by the script does nothing
+but return a response with the body ``Hello world!``; the
+``goodbye_world`` view callable returns a response with the body
+``Goodbye world!``.
+
+.. index::
+ pair: traversal; introduction
+
+.. _traversal_intro:
+
+An Introduction to Traversal
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+If you've run the code listed in :ref`helloworld_imperative` already,
+you've unwittingly configured :mod:`repoze.bfg` to serve an
+application that relies on :term:`traversal`. A full explanation of
+how :mod:`repoze.bfg` locates "the right" :term:`view callable` for a
+given request requires some explanation of :term:`traversal`.
+
+Traversal is part of a mechanism used by :mod:`repoze.bfg` to map the
+URL of some request to a particular :term:`view callable`. It is not
+the only mechanism made available by :mod:`repoze.bfg` that allows the
+mapping a URL to a view callable. Another distinct mode known as
+:term:`URL dispatch` can alternately be used to find a view callable
+based on a URL. However, our sample application uses only
+:term:`traversal`.
+
+In :mod:`repoze.bfg` terms, :term:`traversal` is the act of walking
+over an object graph starting from a :term:`root` object in order to
+find a :term:`context` object and a :term:`view name`. Once a context
+and a view name are found, these two bits of information, plus other
+information from the request are used to look up a :term:`view
+callable`. :mod:`repoze.bfg` bothers to do traversal only because the
+information returned from traversal allows a view callable to be
+found.
+
+The individual path segments of the "path info" portion of a URL (the
+data following the hostname and port number, but before any query
+string elements or fragments, for example the ``/a/b/c`` portion of
+the URL ``http://example.com/a/b/c?foo=1``) are used as "steps" during
+traversal.
+
+.. note:: A useful analogy of how :mod:`repoze.bfg` :term:`traversal`
+ works is available within the chapter section entitled
+ :ref:`traversal_behavior`.
+
+The results of a :term:`traversal` include a :term:`context` and a
+:term:`view name`. The :term:`view name` is the *first* URL path
+segment in the set of path segments "left over" in the results of
+:term:`traversal`. This will either be the empty string (``''``) or a
+non-empty string (one of the path segment strings). The empty string
+represents the :term:`default view` of a context object.
+
+The :term:`default view` is found when all path elements in the URL
+are exhausted before :term:`traversal` returns a :term:`context`
+object, causing the :term:`view name` to be ``''`` (the empty string).
+When no path segments are "left over" after traversal, the
+:term:`default view` for the context found is invoked.
+
+If traversal returns a non-empty :term:`view name`, it means that
+traversal "ran out" of nodes in the graph before it finished
+exhausting all the path segments implied by the path info of the URL:
+no segments are "left over". In this case, because the :term:`view
+name` is non-empty, a *non-default* view callable will be invoked.
+
+The combination of the :term:`context` object and the :term:`view
+name` (and, in more complex configurations, other :term:`predicate`
+values) are used to find "the right" :term:`view callable`, which will
+be invoked after traversal.
+
+The object graph of our hello world application is very simple:
+there's exactly one object in our graph; the default :term:`root`
+object.
+
+Relating Traversal to the Hello World Application
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Our application's :term:`root` object is the *default* root object
+used when one isn't otherwise specified in application configuration.
+This root object does not have a ``__getitem__`` method, thus it has
+no children. Although in a more complex system there can be many
+contexts which URLs resolve to in our application, effectively there
+is only ever one context: the root object.
+
+We have only a single default view registered (the registration for
+the ``hello_world`` view callable). Due to this set of circumstances,
+you can consider the sole possible URL that will resolve to a
+:term:`default view` in this application the root URL ``'/'``. It is
+the only URL that will resolve to the :term:`view name` of ``''`` (the
+empty string).
+
+We have only a single view registered for the :term:`view name`
+``goodbye`` (the registration for the ``goodbye_world`` view
+callable). Due to this set of circumstances, you can consider the
+sole possible URL that will resolve to the ``goodbye_world`` in this
+application the URL ``'/goodbye'`` because it is the only URL that
+will resolve to the :term:`view name` of ``goodbye``.
+
+.. index::
+ pair: imperative; configuration
+ single: Configurator
+
+.. _helloworld_imperative_appconfig:
+
+Application Configuration
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+In the above script, the following code, representing the
+*configuration* of an application which uses the previously defined
+imports and function definitions is placed within the confines of an
+``if`` statement:
+
+.. code-block:: python
+ :linenos:
+
+ if __name__ == '__main__':
+ config = Configurator()
+ config.begin()
+ config.add_view(hello_world)
+ config.add_view(goodbye_world, name='goodbye')
+ config.end()
+ app = config.make_wsgi_app()
+ serve(app)
+
+Let's break this down this piece-by-piece.
+
+Configurator Construction
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. code-block:: python
+ :linenos:
+
+ if __name__ == '__main__':
+ config = Configurator()
+
+The ``if __name__ == '__main__':`` line above represents a Python
+idiom: the code inside this if clause is not invoked unless the script
+is run directly from the command line via, for example, ``python
+helloworld.py`` where the file named ``helloworld.py`` contains the
+entire script body. ``helloworld.py`` in this case is a Python
+*module*. Using the ``if`` clause is necessary (or at least "best
+practice") because code in any Python module may be imported by
+another Python module. By using this idiom, the script is indicating
+that it does not want the code within the ``if`` statement to execute
+if this module is imported; 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:`repoze.bfg.configuration.Configurator` class. The resulting
+``config`` object represents an API which the script uses to configure
+this particular :mod:`repoze.bfg` application.
+
+.. note::
+
+ An instance of the :class:`repoze.bfg.configuration.Configurator`
+ class is a *wrapper* object which mutates an :term:`application
+ registry` as its methods are called. An application registry
+ represents the configuration state of a :mod:`repoze.bfg`
+ application. The ``Configurator`` is not itself an
+ :term:`application registry`, it is a mechanism used to configure
+ an application registry. The underlying application registry
+ object being configured by a ``Configurator`` is available as its
+ ``registry`` attribute.
+
+Beginning Configuration
+~~~~~~~~~~~~~~~~~~~~~~~
+
+.. ignore-next-block
+.. code-block:: python
+
+ config.begin()
+
+The :meth:`repoze.bfg.configuration.Configurator.begin` method tells
+the the system that application configuration has begun. In
+particular, this causes the :term:`application registry` associated
+with this configurator to become the "current" application registry,
+meaning that code which attempts to use the application registry
+:term:`thread local` will obtain the registry associated with the
+configurator. This is an explicit step because it's sometimes
+convenient to use a configurator without causing the registry
+associated with the configurator to become "current".
+
+Adding Configuration
+~~~~~~~~~~~~~~~~~~~~
+
+.. ignore-next-block
+.. code-block:: python
+ :linenos:
+
+ config.add_view(hello_world)
+ config.add_view(goodbye_world, name='goodbye')
+
+Each of these lines calls the
+:meth:`repoze.bfg.configuration.Configurator.add_view` method. The
+``add_view`` method of a configurator registers a :term:`view
+configuration` within the :term:`application registry`. A :term:`view
+configuration` represents a :term:`view callable` which must be
+invoked when a set of circumstances related to the :term:`request` is
+true. This "set of circumstances" is provided as one or more keyword
+arguments to the ``add_view`` method, otherwise known as
+:term:`predicate` arguments.
+
+The line ``config.add_view(hello_world)`` registers the
+``hello_world`` function as a view callable. The ``add_view`` method
+of a Configurator must be called with a view callable object as its
+first argument, so the first argument passed is ``hello_world``
+function we'd like to use as a :term:`view callable`. However, this
+line calls ``add_view`` with a single default :term:`predicate`
+argument, the ``name`` predicate with a value of ``''``, meaning that
+we'd like :mod:`repoze.bfg` to invoke the ``hello_world`` view
+callable for any request for the :term:`default view` of an object.
+
+Our ``hello_world`` :term:`view callable` returns a Response instance
+with a body of ``Hello world!`` in the configuration implied by this
+script. It is configured as a :term:`default view`. Therefore, a
+user agent contacting a server running this application will receive
+the greeting ``Hello world!`` when any :term:`default view` is
+invoked.
+
+.. sidebar:: View Dispatch and Ordering
+
+ When :term:`traversal` is used, :mod:`repoze.bfg` chooses the most
+ specific view callable based *only* on view :term:`predicate`
+ applicability. This is unlike :term:`URL dispatch`, another
+ dispatch mode of :mod:`repoze.bfg` (and other frameworks, like
+ :term:`Pylons` and :term:`Django`) which first uses an ordered
+ routing lookup to resolve the request to a view callable by running
+ it through a relatively-ordered series of URL path matches. We're
+ not really concerned about the finer details of :term:`URL
+ dispatch` right now. It's just useful to use for demonstrative
+ purposes: the ordering of calls to
+ :meth:`repoze.bfg.configuration.Configurator.add_view`` is never
+ very important. We can register ``goodbye_world`` first and
+ ``hello_world`` second; :mod:`repoze.bfg` will still give us the
+ most specific callable when a request is dispatched to it.
+
+The line ``config.add_view(goodbye_world, name='goodbye')`` registers
+the ``goodbye_world`` function as a view callable. The line calls
+``add_view`` with the view callable as the first required positional
+argument, and a :term:`predicate` keyword argument ``name`` with the
+value ``'goodbye'``. This :term:`view configuration` implies that a
+request with a :term:`view name` of ``goodbye`` should cause the
+``goodbye_world`` view callable to be invoked. For the purposes of
+this discussion, the :term:`view name` can be considered the first
+non-empty path segment in the URL: in particular, this view
+configuration will match when the URL is ``/goodbye``.
+
+Our ``goodbye_world`` :term:`view callable` returns a Response
+instance with a body of ``Goodbye world!`` in the configuration
+implied by this script. It is configured as with a :term:`view name`
+predicate of ``goodbye``. Therefore, a user agent contacting a server
+running this application will receive the greeting ``Goodbye world!``
+when the path info part of the request is ``/goodbye``.
+
+Each invocation of the ``add_view`` method implies a :term:`view
+configuration` registration. Each :term:`predicate` provided as a
+keyword argument to the ``add_view`` method narrows the set of
+circumstances which would cause the view configuration's callable to
+be invoked. In general, a greater number of predicates supplied along
+with a view configuration will more strictly limit the applicability
+of its associated view callable. When :mod:`repoze.bfg` processes a
+request, however, the view callable with the *most specific* view
+configuration (the view configuration that matches the largest number
+of predicates) is always invoked.
+
+Earlier we explained that the server would return ``Hello world!`` if
+you visited the *root* (``/``) URL. However, actually, because the
+view configuration registration for the ``hello_world`` view callable
+has no :term:`predicate` arguments, the ``hello_world`` view callable
+is applicable for the :term:`default view` of any :term:`context`
+resulting from a request. This isn't all that interesting in this
+application, because we always only have *one* potential context (the
+root object): it is the only object in the graph.
+
+We've also registered a view configuration for another circumstance:
+the ``goodbye_world`` view callable has a ``name`` predicate of
+``goodbye``, meaning that it will match for requests that have the
+:term:`view name` ``goodbye`` unlike the ``hello_world`` view
+configuration registration, which will only match the default view
+(view name ``''``) of a request. Because :mod:`repoze.bfg` chooses
+the best view configuration for any request, the ``goodbye_world``
+view callable will be used when the URL contains path information that
+ends with ``/goodbye``.
+
+Ending Configuration
+~~~~~~~~~~~~~~~~~~~~
+
+.. ignore-next-block
+.. code-block:: python
+
+ config.end()
+
+The :meth:`repoze.bfg.configuration.Configurator.end` method tells the
+the system that application configuration has ended. It is the
+inverse of :meth:`repoze.bfg.configuration.Configurator.begin`. In
+particular, this causes the :term:`application registry` associated
+with this configurator to no longer be the "current" application
+registry, meaning that code which attempts to use the application
+registry :term:`thread local` will no longer obtain the registry
+associated with the configurator.
+
+.. index::
+ single: make_wsgi_app
+ pair: WSGI; application
+ triple: WSGI; application; creation
+
+WSGI Application Creation
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. ignore-next-block
+.. code-block:: python
+
+ app = config.make_wsgi_app()
+
+After configuring views and ending configuration, the script creates a
+WSGI *application* via the
+:meth:`repoze.bfg.configuration.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 set 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.
+
+The :mod:`repoze.bfg` application object, in particular, is an
+instance of the :class:`repoze.bfg.router.Router` class. It has a
+reference to the :term:`application registry` which resulted from
+method calls to the configurator used to configure it. The Router
+consults the registry to obey the policy choices made by a single
+application. These policy choices were informed by method calls to
+the ``Configurator`` made earlier; in our case, the only policy
+choices made were implied by two calls to the ``add_view`` method,
+telling our application that it should effectively serve up the
+``hello_world`` view callable to any user agent when it visits the
+root URL, and the ``goodbye_world`` view callable to any user agent
+when it visits the URL with the path info ``/goodbye``.
+
+WSGI Application Serving
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. ignore-next-block
+.. code-block:: python
+
+ serve(app)
+
+Finally, we actually serve the application to requestors by starting
+up a WSGI server. We happen to use the :func:`paste.httpserver.serve`
+WSGI server runner, using the default TCP port of 8080, and we pass it
+the ``app`` object (an instance of the
+:class:`repoze.bfg.router.Router` class) as the application we wish to
+serve. This causes the server to start listening on the TCP port. It
+will serve requests forever, or at least until we stop it by killing
+the process which runs it.
+
+Conclusion
+~~~~~~~~~~
+
+Our hello world application is one of the simplest possible
+:mod:`repoze.bfg` applications, configured "imperatively". We can see
+a good deal of what's going on "under the hood" when we configure a
+:mod:`repoze.bfg` application imperatively. However, another mode of
+configuration exists named *declarative* configuration.
+
+.. index::
+ pair: helloworld; declarative
+ single: helloworld
+
+.. _helloworld_declarative:
+
+Hello World, Goodbye World (Declarative)
+----------------------------------------
+
+:mod:`repoze.bfg` can be configured for the same "hello world"
+application "declaratively", if so desired, as described in
+:ref:`declarative_configuration`.
+
+Create a file named ``helloworld.py``:
+
+.. code-block:: python
+ :linenos:
+
+ from webob import Response
+ from paste.httpserver import serve
+ from repoze.bfg.configuration import Configurator
+
+ def hello_world(request):
+ return Response('Hello world!')
+
+ def goodbye_world(request):
+ return Response('Goodbye world!')
+
+ if __name__ == '__main__':
+ config = Configurator()
+ config.begin()
+ config.load_zcml('configure.zcml')
+ config.end()
+ app = config.make_wsgi_app()
+ serve(app)
+
+Create a file named ``configure.zcml`` in the same directory as the
+previously created ``helloworld.py``:
+
+.. code-block:: xml
+ :linenos:
+
+ <configure xmlns="http://namespaces.repoze.org/bfg">
+
+ <include package="repoze.bfg.includes" />
+
+ <view
+ view="helloworld.hello_world"
+ />
+
+ <view
+ name="goodbye"
+ view="helloworld.goodbye_world"
+ />
+
+ </configure>
+
+This pair of files forms an application functionally equivalent to the
+application we created earlier. Let's examine the differences between
+the code described in :ref:`helloworld_imperative` and the code above.
+
+In :ref:`helloworld_imperative_appconfig`, we had the following lines
+within the ``if __name__ == '__main__'`` section of ``helloworld.py``:
+
+.. code-block:: python
+ :linenos:
+
+ if __name__ == '__main__':
+ config = Configurator()
+ config.begin()
+ config.add_view(hello_world)
+ config.add_view(goodbye_world, name='goodbye')
+ config.end()
+ app = config.make_wsgi_app()
+ serve(app)
+
+In our "declarative" code, we've added a call to the
+:meth:`repoze.bfg.configuration.Configurator.load_zcml` method with
+the value ``configure.zcml``, and we've removed the lines which read
+``