summaryrefslogtreecommitdiff
path: root/docs/narr/configuration.rst
blob: 705e5aef5db66a95cc913ec22048647314cf7fd7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
.. _configuration_narr:

Creating Your First :mod:`repoze.bfg` Application
=================================================

The majority of the logic in any web application is completely
application-specific.  For example, the body 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 obviously may
not 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.

.. 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 often initially easier than
   using a framework to create an application, because the developer
   can choose to cede control to library code he has not authored
   selectively, making the resulting application easier to understand.
   When using a framework, the developer is typically required to cede
   a greater portion of control to code he has 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 exists for the platform which you can snap together to
   effectively create your own framework.  In practice, however, using
   an existing 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 and assumptions that fit
   your application requirements.  :mod:`repoze.bfg` is a framework
   that fits a large set of assumptions in the domain of web
   application construction.

As a framework, the primary job of :mod:`repoze.bfg` is to make it
easier for a developer to create an arbitrary web application.  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 deployment as
"configuration".

Most people understand "configuration" as coarse knobs that inform the
high-level operation of a specific application deployment.  For
instance, it's easy to think of the values implied by a ``.ini`` file
which is parsed at application startup time as "configuration".
:mod:`repoze.bfg` extends this pattern all the way out to application
development, using the term "configuration" to express standardized
methods the framework makes available to developers which can be used
to plug code into a deployment of the framework itself.  When you plug
code into the :mod:`repoze.bfg` framework, you are indeed
"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
:mod:`repoze.bfg` to create an application: *imperative* configuration
and *declarative* configuration.  We'll examine both modes in the
sections which follow.

.. warning::

   If you are using Python 2.4 (as opposed to Python 2.5 or 2.6), you
   will need to install the ``wsgiref`` package for the examples in
   this chapter to work.  Use ``easy_install wsgiref`` to get it
   installed.

.. _helloworld_imperative:

Hello World, Configured Imperatively
------------------------------------

Experienced Python programmers may find the "imperative" configuration
mechanism fits the way they already do things. This is the configuration
mode in which developers cede the least amount of control to the framework.
Because of this, it is also the easiest configuration mode to understand.

Here's one of the simplest :mod:`repoze.bfg` applications, configured
imperatively:

.. code-block:: python
   :linenos:

   from webob import Response
   from wsgiref import simple_server
   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.add_view(hello_world)
       config.add_view(goodbye_world, name='goodbye')
       app = config.make_wsgi_app()
       simple_server.make_server('', 8080, app).serve_forever()

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, this code starts an HTTP server
on port 8080.  When 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 wsgiref import simple_server
   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
``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 ``wsgiref.simple_server`` server is used in this
example as a WSGI server, purely for convenience.  :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!')

Both functions accepts a single argument (``request``), and each
returns an instance of the ``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!``.

.. _traversal_intro:

An Introduction to Traversal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If you've run the code in this tutorial already, you've actually
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 a *directed graph* of objects from a :term:`root` object using
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``) in order to find a
:term:`context` object and a :term:`view name`.  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.

We need to use an analogy to clarify how traversal works on an
arbitrary object graph.  Let's imagine an inexperienced UNIX computer
user, wishing only to use the command line to find a file and to
invoke the ``cat`` command against that file.  Because he is
inexperienced, the only commands he knows how to use are ``cd``, which
changes the current directory and ``cat``, which prints the contents
of a file.  And because he is inexperienced, he doesn't understand
that ``cat`` can take an absolute path specification as an argument,
so he doesn't know that you can issue a single command command ``cat
/an/absolute/path`` to get the desired result.  Instead, this user
believes he must issue the ``cd`` command, starting from the root, for
each intermediate path segment, *even the path segment that represents
the file itself*.  Once he gets an error (because you cannot
succesfully ``cd`` into a file), he knows he has reached the file he
wants, and he will be able to execute ``cat`` against the resulting
path segment.

This inexperienced user's attempt to execute ``cat`` against the file
named ``/fiz/buz/myfile`` might be to issue the following set of UNIX
commands:

.. code-block::  bash
   :linenos:

   cd /
   cd fiz
   cd buz
   cd myfile

The user now know he has found a *file*, because the ``cd`` command
issues an error when he executed ``cd myfile``.  Now he knows that he
can run the ``cat`` command:

.. code-block::  bash
   :linenos:

   cat myfile

The contents of ``myfile`` are now printed on the user's behalf.

:mod:`repoze.bfg` is very much like this inexperienced UNIX user as it
uses :term:`traversal` against an object graph.  In this analogy, we
can map the ``cat`` program to the :mod:`repoze.bfg` concept of a
:term:`view callable`: it is a program that can be run against some
:term:`context`.  The file being operated on in this analogy is the
:term:`context` object; the context is the "last object found" in a
traversal.  The directory structure is the object graph being
traversed.  The act of progressively changing directories to find the
file as well as the handling of a ``cd`` error as a stop condition is
analogous to :term:`traversal`.

Here's an image that depicts the :mod:`repoze.bfg` traversal process
graphically as a flowchart:

.. image:: modelgraphtraverser.png

The object graph is traversed, beginning at a root object, represented
by the root URL (``/``); if there are further path segments in the
path info of the request being processed, the root object's
``__getitem__`` is called with the next path segment, and it is
expected to return another graph object.  The resulting object's
``__getitem__`` is called with the very next path segment, and it is
expected to return another graph object.  This happens *ad infinitum*
until all path segments are exhausted.  If at any point during
traversal any node in the graph doesn't *have* a ``__getitem__``
method, or if the ``__getitem__`` of a node raises a ``KeyError``,
traversal ends immediately, and the node becomes the :term:`context`.

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" during
: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 segements 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.

Apologies that this digression was required; on with the chapter.

.. note:: 

   For more in-depth information about traversal-related concepts, see
   :ref:`traversal_chapter`.

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``.

.. _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.add_view(hello_world)
       config.add_view(goodbye_world, name='goodbye')
       app = config.make_wsgi_app()
       simple_server.make_server('', 8080, app).serve_forever()

Let's break this down this piece-by-piece:

.. 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
``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 ``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.

.. code-block:: python
   :linenos:

       config.add_view(hello_world)
       config.add_view(goodbye_world, name='goodbye')

Each of these lines calls the ``add_view`` method of the
``Configurator`` API.  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 ``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``.

WSGI Application Creation
~~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: python
   :linenos:

       app = config.make_wsgi_app()

After configuring views, the script creates a WSGI *application* via
the ``config.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 ``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
~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: python
   :linenos:

       simple_server.make_server('', 8080, app).serve_forever()

Finally, we actually serve the application to requestors by starting
up a WSGI server.  We happen to use the ``wsgiref.simple_server`` WSGI
server implementation, telling it to serve the application on TCP port
8080, and we pass it the ``app`` object (an instance of
``repoze.bfg.router.Router``) as the application we wish to serve.  We
then call the ``serve_forever`` method of the result to
``simple_server.make_server``, causing 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.

Hello World, Configured Declaratively
-------------------------------------

: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.

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::

   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.

In a file named ``helloworld.py``:

.. code-block:: python
   :linenos:

   from webob import Response
   from wsgiref import simple_server
   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.load_zcml('configure.zcml)
       app = config.make_wsgi_app()
       simple_server.make_server('', 8080, app).serve_forever()

In 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.add_view(hello_world)
       config.add_view(goodbye_world, name='goodbye')
       app = config.make_wsgi_app()
       simple_server.make_server('', 8080, app).serve_forever()

In our "declarative" code, we've added a call to the ``load_zcml``
method of the ``Configurator`` 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:

.. code-block:: python
   :linenos:

   if __name__ == '__main__':
       config = Configurator()
       config.load_zcml('configure.zcml')
       app = config.make_wsgi_app()
       simple_server.make_server('', 8080, app).serve_forever()

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:

.. 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>

The ``<configure>`` Tag
~~~~~~~~~~~~~~~~~~~~~~~

The ``configure.zcml`` ZCML file contains this bit of XML:

.. code-block:: xml
   :linenos:

    <configure xmlns="http://namespaces.repoze.org/bfg">
       ... body ...
    </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 tag, which acts as the root XML
tag.  Usually, the start tag of the ``<configure>`` container tag has
a default namespace associated with it. In the file above, the
``xmlns="http://namepaces.repoze.org/bfg"`` attribute of the
``configure`` start tag names the default XML namespace, which is
``http://namespaces.repoze.org/bfg``.  See
:ref:`word_on_xml_namespaces` for more information about XML
namespaces.

The ``<include>`` Tag
~~~~~~~~~~~~~~~~~~~~~

The ``configure.zcml`` ZCML file contains this bit of XML within the
``<configure>`` root tag:

.. code-block:: xml
   :linenos:

      <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`
``repoze.bfg.includes``, as specified by its ``package`` attribute.
This particular ``<include>`` declaration is required because it
actually allows subseqent 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
``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"/>

The ``<include>`` tag that includes the ZCML statements implied by the
``configure.zcml`` file from the Python package named
``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.

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:

.. 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 ``add_view`` method of the ``Configurator`` object 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 ``Configuration.add_view``
doesn't matter (see the sidebar above 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"
           />

.. topic:: Goodbye Before Hello

  .. code-block:: xml
     :linenos:

        <view
           name="goodbye"
           view="helloworld.goodbye_world"
           />

        <view
           view="helloworld.hello_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 on the ``Configurator`` object on your
behalf.

ZCML Conflict Detection
~~~~~~~~~~~~~~~~~~~~~~~

An 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:

.. code-block:: xml
   :linenos:

    <configure xmlns="http://namespaces.repoze.org/bfg">

      <include package="repoze.bfg.includes" />

      <view
         view="helloworld.hello_world"
         />

      <view
         view="helloworld.hello_world"
         />

    </configure>

If you try to use this ZCML file as the source of ZCML for an
application, a ``ConfigurationError`` will be raised when you attempt
to start the application with information about which tags might have
conflicted.

.. _word_on_xml_namespaces:

A Word On XML Namespaces
~~~~~~~~~~~~~~~~~~~~~~~~

Using the ``http://namespaces.repoze.org/bfg`` namespace as the
default XML namespace isn't strictly necessary; you can use a
different default namespace as the default.  However, if you do, the
declaration tags which are defined by :mod:`repoze.bfg` such as the
``<view>`` declaration tag will need to be defined in such a way that
the XML parser that :mod:`repoze.bfg` uses knows which namespace the
:mod:`repoze.bfg` tags are associated with.  For example, the
following files are all completely equivalent:

.. topic:: Use of A Non-Default XML Namespace

  .. code-block:: xml
     :linenos:

      <configure xmlns="http://namespaces.zope.org/zope"
                 xmlns:bfg="http://namespaces.repoze.org/bfg">

        <include package="repoze.bfg.includes" />

        <bfg:view
           view="helloworld.hello_world"
           />

      </configure>

.. topic:: Use of A Per-Tag XML Namespace Without A Default XML Namespace

  .. code-block:: xml
     :linenos:

      <configure>

        <include package="repoze.bfg.includes" />

        <view xmlns="http://namespaces.repoze.org/bfg"
           view="helloworld.hello_world"
           />

      </configure>

For more information about XML namespaces, see `this older, but simple
XML.com article <http://www.xml.com/pub/a/1999/01/namespaces.html>`_.

Conclusions
-----------

.. sidebar::  Which Configuration Mode Should I Use?

  We recommend declarative configuration (ZMCL), 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.

: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.

For more information about the API of the ``Configurator`` object, see
:ref:`configuration_module`.  The equivalent ZCML declaration tags are
introduced in narrative documentation chapters as necessary.

For more information about :term:`traversal`, see
:ref:`traversal_chapter`.

For more information about :term:`view configuration`, see
:ref:`views_chapter`.