Ignore:
Timestamp:
Mar 19, 2014, 11:11:30 AM (11 years ago)
Author:
dmik
Message:

python: Update vendor to 2.7.6.

Location:
python/vendor/current/Doc/howto
Files:
7 added
1 deleted
10 edited

Legend:

Unmodified
Added
Removed
  • python/vendor/current/Doc/howto/cporting.rst

    r2 r388  
    11.. highlightlang:: c
    22
    3 ********************************
    4 Porting Extension Modules to 3.0
    5 ********************************
     3.. _cporting-howto:
     4
     5*************************************
     6Porting Extension Modules to Python 3
     7*************************************
    68
    79:author: Benjamin Peterson
     
    1012.. topic:: Abstract
    1113
    12    Although changing the C-API was not one of Python 3.0's objectives, the many
    13    Python level changes made leaving 2.x's API intact impossible.  In fact, some
    14    changes such as :func:`int` and :func:`long` unification are more obvious on
    15    the C level.  This document endeavors to document incompatibilities and how
    16    they can be worked around.
     14   Although changing the C-API was not one of Python 3's objectives,
     15   the many Python-level changes made leaving Python 2's API intact
     16   impossible.  In fact, some changes such as :func:`int` and
     17   :func:`long` unification are more obvious on the C level.  This
     18   document endeavors to document incompatibilities and how they can
     19   be worked around.
    1720
    1821
     
    2023=======================
    2124
    22 The easiest way to compile only some code for 3.0 is to check if
    23 :cmacro:`PY_MAJOR_VERSION` is greater than or equal to 3. ::
     25The easiest way to compile only some code for Python 3 is to check
     26if :c:macro:`PY_MAJOR_VERSION` is greater than or equal to 3. ::
    2427
    2528   #if PY_MAJOR_VERSION >= 3
     
    3437======================
    3538
    36 Python 3.0 merged together some types with similar functions while cleanly
     39Python 3 merged together some types with similar functions while cleanly
    3740separating others.
    3841
     
    4245
    4346
    44 Python 3.0's :func:`str` (``PyString_*`` functions in C) type is equivalent to
    45 2.x's :func:`unicode` (``PyUnicode_*``).  The old 8-bit string type has become
    46 :func:`bytes`.  Python 2.6 and later provide a compatibility header,
     47Python 3's :func:`str` (``PyString_*`` functions in C) type is equivalent to
     48Python 2's :func:`unicode` (``PyUnicode_*``).  The old 8-bit string type has
     49become :func:`bytes`.  Python 2.6 and later provide a compatibility header,
    4750:file:`bytesobject.h`, mapping ``PyBytes`` names to ``PyString`` ones.  For best
    48 compatibility with 3.0, :ctype:`PyUnicode` should be used for textual data and
    49 :ctype:`PyBytes` for binary data.  It's also important to remember that
    50 :ctype:`PyBytes` and :ctype:`PyUnicode` in 3.0 are not interchangeable like
    51 :ctype:`PyString` and :ctype:`PyString` are in 2.x.  The following example shows
    52 best practices with regards to :ctype:`PyUnicode`, :ctype:`PyString`, and
    53 :ctype:`PyBytes`. ::
     51compatibility with Python 3, :c:type:`PyUnicode` should be used for textual data and
     52:c:type:`PyBytes` for binary data.  It's also important to remember that
     53:c:type:`PyBytes` and :c:type:`PyUnicode` in Python 3 are not interchangeable like
     54:c:type:`PyString` and :c:type:`PyUnicode` are in Python 2.  The following example
     55shows best practices with regards to :c:type:`PyUnicode`, :c:type:`PyString`,
     56and :c:type:`PyBytes`. ::
    5457
    5558   #include "stdlib.h"
     
    9396--------------------
    9497
    95 In Python 3.0, there is only one integer type.  It is called :func:`int` on the
    96 Python level, but actually corresponds to 2.x's :func:`long` type.  In the
    97 C-API, ``PyInt_*`` functions are replaced by their ``PyLong_*`` neighbors.  The
    98 best course of action here is using the ``PyInt_*`` functions aliased to
    99 ``PyLong_*`` found in :file:`intobject.h`.  The abstract ``PyNumber_*`` APIs
    100 can also be used in some cases. ::
    101 
    102    #include "Python.h"
    103    #include "intobject.h"
    104 
    105    static PyObject *
    106    add_ints(PyObject *self, PyObject *args) {
    107        int one, two;
    108        PyObject *result;
    109 
    110        if (!PyArg_ParseTuple(args, "ii:add_ints", &one, &two))
    111            return NULL;
    112 
    113        return PyInt_FromLong(one + two);
    114    }
    115 
     98Python 3 has only one integer type, :func:`int`.  But it actually
     99corresponds to Python 2's :func:`long` type--the :func:`int` type
     100used in Python 2 was removed.  In the C-API, ``PyInt_*`` functions
     101are replaced by their ``PyLong_*`` equivalents.
    116102
    117103
     
    119105===============================
    120106
    121 Python 3.0 has a revamped extension module initialization system.  (See PEP
    122 :pep:`3121`.)  Instead of storing module state in globals, they should be stored
    123 in an interpreter specific structure.  Creating modules that act correctly in
    124 both 2.x and 3.0 is tricky.  The following simple example demonstrates how. ::
     107Python 3 has a revamped extension module initialization system.  (See
     108:pep:`3121`.)  Instead of storing module state in globals, they should
     109be stored in an interpreter specific structure.  Creating modules that
     110act correctly in both Python 2 and Python 3 is tricky.  The following
     111simple example demonstrates how. ::
    125112
    126113   #include "Python.h"
     
    208195
    209196
     197CObject replaced with Capsule
     198=============================
     199
     200The :c:type:`Capsule` object was introduced in Python 3.1 and 2.7 to replace
     201:c:type:`CObject`.  CObjects were useful,
     202but the :c:type:`CObject` API was problematic: it didn't permit distinguishing
     203between valid CObjects, which allowed mismatched CObjects to crash the
     204interpreter, and some of its APIs relied on undefined behavior in C.
     205(For further reading on the rationale behind Capsules, please see :issue:`5630`.)
     206
     207If you're currently using CObjects, and you want to migrate to 3.1 or newer,
     208you'll need to switch to Capsules.
     209:c:type:`CObject` was deprecated in 3.1 and 2.7 and completely removed in
     210Python 3.2.  If you only support 2.7, or 3.1 and above, you
     211can simply switch to :c:type:`Capsule`.  If you need to support Python 3.0,
     212or versions of Python earlier than 2.7,
     213you'll have to support both CObjects and Capsules.
     214(Note that Python 3.0 is no longer supported, and it is not recommended
     215for production use.)
     216
     217The following example header file :file:`capsulethunk.h` may
     218solve the problem for you.  Simply write your code against the
     219:c:type:`Capsule` API and include this header file after
     220:file:`Python.h`.  Your code will automatically use Capsules
     221in versions of Python with Capsules, and switch to CObjects
     222when Capsules are unavailable.
     223
     224:file:`capsulethunk.h` simulates Capsules using CObjects.  However,
     225:c:type:`CObject` provides no place to store the capsule's "name".  As a
     226result the simulated :c:type:`Capsule` objects created by :file:`capsulethunk.h`
     227behave slightly differently from real Capsules.  Specifically:
     228
     229  * The name parameter passed in to :c:func:`PyCapsule_New` is ignored.
     230
     231  * The name parameter passed in to :c:func:`PyCapsule_IsValid` and
     232    :c:func:`PyCapsule_GetPointer` is ignored, and no error checking
     233    of the name is performed.
     234
     235  * :c:func:`PyCapsule_GetName` always returns NULL.
     236
     237  * :c:func:`PyCapsule_SetName` always raises an exception and
     238    returns failure.  (Since there's no way to store a name
     239    in a CObject, noisy failure of :c:func:`PyCapsule_SetName`
     240    was deemed preferable to silent failure here.  If this is
     241    inconvenient, feel free to modify your local
     242    copy as you see fit.)
     243
     244You can find :file:`capsulethunk.h` in the Python source distribution
     245as :source:`Doc/includes/capsulethunk.h`.  We also include it here for
     246your convenience:
     247
     248.. literalinclude:: ../includes/capsulethunk.h
     249
     250
     251
    210252Other options
    211253=============
     
    213255If you are writing a new extension module, you might consider `Cython
    214256<http://www.cython.org>`_.  It translates a Python-like language to C.  The
    215 extension modules it creates are compatible with Python 3.x and 2.x.
    216 
     257extension modules it creates are compatible with Python 3 and Python 2.
     258
  • python/vendor/current/Doc/howto/curses.rst

    r2 r388  
    119119messed up when the application dies without restoring the terminal to its
    120120previous state.  In Python this commonly happens when your code is buggy and
    121 raises an uncaught exception.  Keys are no longer be echoed to the screen when
     121raises an uncaught exception.  Keys are no longer echoed to the screen when
    122122you type them, for example, which makes using the shell difficult.
    123123
     
    145145window of a given size, returning the new window object. ::
    146146
    147    begin_x = 20 ; begin_y = 7
    148    height = 5 ; width = 40
     147   begin_x = 20; begin_y = 7
     148   height = 5; width = 40
    149149   win = curses.newwin(height, width, begin_y, begin_x)
    150150
     
    185185   for y in range(0, 100):
    186186       for x in range(0, 100):
    187            try: pad.addch(y,x, ord('a') + (x*x+y*y) % 26 )
    188            except curses.error: pass
     187           try:
     188               pad.addch(y,x, ord('a') + (x*x+y*y) % 26)
     189           except curses.error:
     190               pass
    189191
    190192   #  Displays a section of the pad in the middle of the screen
    191    pad.refresh( 0,0, 5,5, 20,75)
     193   pad.refresh(0,0, 5,5, 20,75)
    192194
    193195The :func:`refresh` call displays a section of the pad in the rectangle
     
    272274attribute for each cell on the screen.
    273275
    274 An attribute is a integer, each bit representing a different attribute.  You can
     276An attribute is an integer, each bit representing a different attribute.  You can
    275277try to display text with multiple attribute bits set, but curses doesn't
    276278guarantee that all the possible combinations are available, or that they're all
     
    301303   stdscr.refresh()
    302304
    303 The curses library also supports color on those terminals that provide it, The
     305The curses library also supports color on those terminals that provide it. The
    304306most common such terminal is probably the Linux console, followed by color
    305307xterms.
     
    322324An example, which displays a line of text using color pair 1::
    323325
    324    stdscr.addstr( "Pretty text", curses.color_pair(1) )
     326   stdscr.addstr("Pretty text", curses.color_pair(1))
    325327   stdscr.refresh()
    326328
     
    344346with::
    345347
    346    stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1) )
     348   stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1))
    347349
    348350Very fancy terminals can change the definitions of the actual colors to a given
     
    382384   while 1:
    383385       c = stdscr.getch()
    384        if c == ord('p'): PrintDocument()
    385        elif c == ord('q'): break  # Exit the while()
    386        elif c == curses.KEY_HOME: x = y = 0
     386       if c == ord('p'):
     387           PrintDocument()
     388       elif c == ord('q'):
     389           break  # Exit the while()
     390       elif c == curses.KEY_HOME:
     391           x = y = 0
    387392
    388393The :mod:`curses.ascii` module supplies ASCII class membership functions that
     
    434439
    435440The ncurses FAQ: http://invisible-island.net/ncurses/ncurses.faq.html
    436 
  • python/vendor/current/Doc/howto/doanddont.rst

    r2 r388  
    3333valid, no more than having a smart lawyer makes a man innocent. Do not use it
    3434like that ever. Even in versions where it was accepted, it made the function
    35 execution slower, because the compiler could not be certain which names are
    36 local and which are global. In Python 2.1 this construct causes warnings, and
     35execution slower, because the compiler could not be certain which names were
     36local and which were global. In Python 2.1 this construct causes warnings, and
    3737sometimes even errors.
    3838
     
    4747some module grows additional functions or classes.
    4848
    49 One of the most awful question asked on the newsgroup is why this code::
     49One of the most awful questions asked on the newsgroup is why this code::
    5050
    5151   f = open("www")
     
    114114This is a "don't" which is much weaker than the previous "don't"s but is still
    115115something you should not do if you don't have good reasons to do that. The
    116 reason it is usually bad idea is because you suddenly have an object which lives
     116reason it is usually a bad idea is because you suddenly have an object which lives
    117117in two separate namespaces. When the binding in one namespace changes, the
    118118binding in the other will not, so there will be a discrepancy between them. This
     
    145145
    146146Python has the ``except:`` clause, which catches all exceptions. Since *every*
    147 error in Python raises an exception, this makes many programming errors look
    148 like runtime problems, and hinders the debugging process.
    149 
    150 The following code shows a great example::
     147error in Python raises an exception, using ``except:`` can make many
     148programming errors look like runtime problems, which hinders the debugging
     149process.
     150
     151The following code shows a great example of why this is bad::
    151152
    152153   try:
     
    155156       sys.exit("could not open file!")
    156157
    157 The second line triggers a :exc:`NameError` which is caught by the except
    158 clause. The program will exit, and you will have no idea that this has nothing
    159 to do with the readability of ``"file"``.
    160 
    161 The example above is better written ::
     158The second line triggers a :exc:`NameError`, which is caught by the except
     159clause. The program will exit, and the error message the program prints will
     160make you think the problem is the readability of ``"file"`` when in fact
     161the real error has nothing to do with ``"file"``.
     162
     163A better way to write the above is ::
    162164
    163165   try:
    164        foo = opne("file") # will be changed to "open" as soon as we run it
     166       foo = opne("file")
    165167   except IOError:
    166168       sys.exit("could not open file")
    167169
    168 There are some situations in which the ``except:`` clause is useful: for
    169 example, in a framework when running callbacks, it is good not to let any
    170 callback disturb the framework.
     170When this is run, Python will produce a traceback showing the :exc:`NameError`,
     171and it will be immediately apparent what needs to be fixed.
     172
     173.. index:: bare except, except; bare
     174
     175Because ``except:`` catches *all* exceptions, including :exc:`SystemExit`,
     176:exc:`KeyboardInterrupt`, and :exc:`GeneratorExit` (which is not an error and
     177should not normally be caught by user code), using a bare ``except:`` is almost
     178never a good idea.  In situations where you need to catch all "normal" errors,
     179such as in a framework that runs callbacks, you can catch the base class for
     180all normal exceptions, :exc:`Exception`.  Unfortunately in Python 2.x it is
     181possible for third-party code to raise exceptions that do not inherit from
     182:exc:`Exception`, so in Python 2.x there are some cases where you may have to
     183use a bare ``except:`` and manually re-raise the exceptions you don't want
     184to catch.
    171185
    172186
     
    186200       return open(file).readline()
    187201
    188 Consider the case the file gets deleted between the time the call to
    189 :func:`os.path.exists` is made and the time :func:`open` is called. That means
    190 the last line will throw an :exc:`IOError`. The same would happen if *file*
    191 exists but has no read permission. Since testing this on a normal machine on
    192 existing and non-existing files make it seem bugless, that means in testing the
    193 results will seem fine, and the code will get shipped. Then an unhandled
    194 :exc:`IOError` escapes to the user, who has to watch the ugly traceback.
    195 
    196 Here is a better way to do it. ::
     202Consider the case where the file gets deleted between the time the call to
     203:func:`os.path.exists` is made and the time :func:`open` is called. In that
     204case the last line will raise an :exc:`IOError`.  The same thing would happen
     205if *file* exists but has no read permission.  Since testing this on a normal
     206machine on existent and non-existent files makes it seem bugless, the test
     207results will seem fine, and the code will get shipped.  Later an unhandled
     208:exc:`IOError` (or perhaps some other :exc:`EnvironmentError`) escapes to the
     209user, who gets to watch the ugly traceback.
     210
     211Here is a somewhat better way to do it. ::
    197212
    198213   def get_status(file):
    199214       try:
    200215           return open(file).readline()
    201        except (IOError, OSError):
    202            print "file not found"
     216       except EnvironmentError as err:
     217           print "Unable to open file: {}".format(err)
    203218           sys.exit(1)
    204219
    205 In this version, \*either\* the file gets opened and the line is read (so it
    206 works even on flaky NFS or SMB connections), or the message is printed and the
    207 application aborted.
    208 
    209 Still, :func:`get_status` makes too many assumptions --- that it will only be
    210 used in a short running script, and not, say, in a long running server. Sure,
    211 the caller could do something like ::
     220In this version, *either* the file gets opened and the line is read (so it
     221works even on flaky NFS or SMB connections), or an error message is printed
     222that provides all the available information on why the open failed, and the
     223application is aborted.
     224
     225However, even this version of :func:`get_status` makes too many assumptions ---
     226that it will only be used in a short running script, and not, say, in a long
     227running server. Sure, the caller could do something like ::
    212228
    213229   try:
     
    216232       status = None
    217233
    218 So, try to make as few ``except`` clauses in your code --- those will usually be
    219 a catch-all in the :func:`main`, or inside calls which should always succeed.
    220 
    221 So, the best version is probably ::
     234But there is a better way.  You should try to use as few ``except`` clauses in
     235your code as you can --- the ones you do use will usually be inside calls which
     236should always succeed, or a catch-all in a main function.
     237
     238So, an even better version of :func:`get_status()` is probably ::
    222239
    223240   def get_status(file):
    224241       return open(file).readline()
    225242
    226 The caller can deal with the exception if it wants (for example, if it  tries
     243The caller can deal with the exception if it wants (for example, if it tries
    227244several files in a loop), or just let the exception filter upwards to *its*
    228245caller.
    229246
    230 The last version is not very good either --- due to implementation details, the
    231 file would not be closed when an exception is raised until the handler finishes,
    232 and perhaps not at all in non-C implementations (e.g., Jython). ::
     247But the last version still has a serious problem --- due to implementation
     248details in CPython, the file would not be closed when an exception is raised
     249until the exception handler finishes; and, worse, in other implementations
     250(e.g., Jython) it might not be closed at all regardless of whether or not
     251an exception is raised.
     252
     253The best version of this function uses the ``open()`` call as a context
     254manager, which will ensure that the file gets closed as soon as the
     255function returns::
    233256
    234257   def get_status(file):
    235        fp = open(file)
    236        try:
     258       with open(file) as fp:
    237259           return fp.readline()
    238        finally:
    239            fp.close()
    240260
    241261
     
    262282:func:`splitext`.
    263283
    264 There are also many useful built-in functions people seem not to be aware of for
    265 some reason: :func:`min` and :func:`max` can find the minimum/maximum of any
    266 sequence with comparable semantics, for example, yet many people write their own
    267 :func:`max`/:func:`min`. Another highly useful function is :func:`reduce`. A
    268 classical use of :func:`reduce` is something like ::
    269 
    270    import sys, operator
    271    nums = map(float, sys.argv[1:])
    272    print reduce(operator.add, nums)/len(nums)
    273 
    274 This cute little script prints the average of all numbers given on the command
    275 line. The :func:`reduce` adds up all the numbers, and the rest is just some
    276 pre- and postprocessing.
    277 
    278 On the same note, note that :func:`float`, :func:`int` and :func:`long` all
    279 accept arguments of type string, and so are suited to parsing --- assuming you
    280 are ready to deal with the :exc:`ValueError` they raise.
     284There are also many useful built-in functions people seem not to be aware of
     285for some reason: :func:`min` and :func:`max` can find the minimum/maximum of
     286any sequence with comparable semantics, for example, yet many people write
     287their own :func:`max`/:func:`min`. Another highly useful function is
     288:func:`reduce` which can be used to repeatly apply a binary operation to a
     289sequence, reducing it to a single value.  For example, compute a factorial
     290with a series of multiply operations::
     291
     292   >>> n = 4
     293   >>> import operator
     294   >>> reduce(operator.mul, range(1, n+1))
     295   24
     296
     297When it comes to parsing numbers, note that :func:`float`, :func:`int` and
     298:func:`long` all accept string arguments and will reject ill-formed strings
     299by raising an :exc:`ValueError`.
    281300
    282301
  • python/vendor/current/Doc/howto/functional.rst

    r2 r388  
    55:Author: A. M. Kuchling
    66:Release: 0.31
    7 
    8 (This is a first draft.  Please send comments/error reports/suggestions to
    9 amk@amk.ca.)
    107
    118In this document, we'll take a tour of Python's features suitable for
     
    4845  variants) and Haskell.
    4946
    50 The designers of some computer languages choose to emphasize one
    51 particular approach to programming.  This often makes it difficult to
    52 write programs that use a different approach.  Other languages are
    53 multi-paradigm languages that support several different approaches.
    54 Lisp, C++, and Python are multi-paradigm; you can write programs or
    55 libraries that are largely procedural, object-oriented, or functional
    56 in all of these languages.  In a large program, different sections
    57 might be written using different approaches; the GUI might be
    58 object-oriented while the processing logic is procedural or
     47The designers of some computer languages choose to emphasize one particular
     48approach to programming.  This often makes it difficult to write programs that
     49use a different approach.  Other languages are multi-paradigm languages that
     50support several different approaches.  Lisp, C++, and Python are
     51multi-paradigm; you can write programs or libraries that are largely
     52procedural, object-oriented, or functional in all of these languages.  In a
     53large program, different sections might be written using different approaches;
     54the GUI might be object-oriented while the processing logic is procedural or
    5955functional, for example.
    6056
     
    249245and ``"not in"`` operators also support iterators: ``X in iterator`` is true if
    250246X is found in the stream returned by the iterator.  You'll run into obvious
    251 problems if the iterator is infinite; ``max()``, ``min()``, and ``"not in"``
     247problems if the iterator is infinite; ``max()``, ``min()``
    252248will never return, and if the element X never appears in the stream, the
    253 ``"in"`` operator won't return either.
     249``"in"`` and ``"not in"`` operators won't return either.
    254250
    255251Note that you can only go forward in an iterator; there's no way to get the
     
    336332List comprehensions and generator expressions (short form: "listcomps" and
    337333"genexps") are a concise notation for such operations, borrowed from the
    338 functional programming language Haskell (http://www.haskell.org).  You can strip
     334functional programming language Haskell (http://www.haskell.org/).  You can strip
    339335all the whitespace from a stream of strings with the following code::
    340336
     
    11191115
    11201116
    1121 
    1122 The functional module
    1123 ---------------------
    1124 
    1125 Collin Winter's `functional module <http://oakwinter.com/code/functional/>`__
    1126 provides a number of more advanced tools for functional programming. It also
    1127 reimplements several Python built-ins, trying to make them more intuitive to
    1128 those used to functional programming in other languages.
    1129 
    1130 This section contains an introduction to some of the most important functions in
    1131 ``functional``; full documentation can be found at `the project's website
    1132 <http://oakwinter.com/code/functional/documentation/>`__.
    1133 
    1134 ``compose(outer, inner, unpack=False)``
    1135 
    1136 The ``compose()`` function implements function composition.  In other words, it
    1137 returns a wrapper around the ``outer`` and ``inner`` callables, such that the
    1138 return value from ``inner`` is fed directly to ``outer``.  That is, ::
    1139 
    1140     >>> def add(a, b):
    1141     ...     return a + b
    1142     ...
    1143     >>> def double(a):
    1144     ...     return 2 * a
    1145     ...
    1146     >>> compose(double, add)(5, 6)
    1147     22
    1148 
    1149 is equivalent to ::
    1150 
    1151     >>> double(add(5, 6))
    1152     22
    1153 
    1154 The ``unpack`` keyword is provided to work around the fact that Python functions
    1155 are not always `fully curried <http://en.wikipedia.org/wiki/Currying>`__.  By
    1156 default, it is expected that the ``inner`` function will return a single object
    1157 and that the ``outer`` function will take a single argument. Setting the
    1158 ``unpack`` argument causes ``compose`` to expect a tuple from ``inner`` which
    1159 will be expanded before being passed to ``outer``. Put simply, ::
    1160 
    1161     compose(f, g)(5, 6)
    1162 
    1163 is equivalent to::
    1164 
    1165     f(g(5, 6))
    1166 
    1167 while ::
    1168 
    1169     compose(f, g, unpack=True)(5, 6)
    1170 
    1171 is equivalent to::
    1172 
    1173     f(*g(5, 6))
    1174 
    1175 Even though ``compose()`` only accepts two functions, it's trivial to build up a
    1176 version that will compose any number of functions. We'll use ``reduce()``,
    1177 ``compose()`` and ``partial()`` (the last of which is provided by both
    1178 ``functional`` and ``functools``). ::
    1179 
    1180     from functional import compose, partial
    1181 
    1182     multi_compose = partial(reduce, compose)
    1183 
    1184 
    1185 We can also use ``map()``, ``compose()`` and ``partial()`` to craft a version of
    1186 ``"".join(...)`` that converts its arguments to string::
    1187 
    1188     from functional import compose, partial
    1189 
    1190     join = compose("".join, partial(map, str))
    1191 
    1192 
    1193 ``flip(func)``
    1194 
    1195 ``flip()`` wraps the callable in ``func`` and causes it to receive its
    1196 non-keyword arguments in reverse order. ::
    1197 
    1198     >>> def triple(a, b, c):
    1199     ...     return (a, b, c)
    1200     ...
    1201     >>> triple(5, 6, 7)
    1202     (5, 6, 7)
    1203     >>>
    1204     >>> flipped_triple = flip(triple)
    1205     >>> flipped_triple(5, 6, 7)
    1206     (7, 6, 5)
    1207 
    1208 ``foldl(func, start, iterable)``
    1209 
    1210 ``foldl()`` takes a binary function, a starting value (usually some kind of
    1211 'zero'), and an iterable.  The function is applied to the starting value and the
    1212 first element of the list, then the result of that and the second element of the
    1213 list, then the result of that and the third element of the list, and so on.
    1214 
    1215 This means that a call such as::
    1216 
    1217     foldl(f, 0, [1, 2, 3])
    1218 
    1219 is equivalent to::
    1220 
    1221     f(f(f(0, 1), 2), 3)
    1222 
    1223 
    1224 ``foldl()`` is roughly equivalent to the following recursive function::
    1225 
    1226     def foldl(func, start, seq):
    1227         if len(seq) == 0:
    1228             return start
    1229 
    1230         return foldl(func, func(start, seq[0]), seq[1:])
    1231 
    1232 Speaking of equivalence, the above ``foldl`` call can be expressed in terms of
    1233 the built-in ``reduce`` like so::
    1234 
    1235     reduce(f, [1, 2, 3], 0)
    1236 
    1237 
    1238 We can use ``foldl()``, ``operator.concat()`` and ``partial()`` to write a
    1239 cleaner, more aesthetically-pleasing version of Python's ``"".join(...)``
    1240 idiom::
    1241 
    1242     from functional import foldl, partial from operator import concat
    1243 
    1244     join = partial(foldl, concat, "")
    1245 
    1246 
    12471117Revision History and Acknowledgements
    12481118=====================================
     
    13001170Mertz also wrote a 3-part series of articles on functional programming
    13011171for IBM's DeveloperWorks site; see
    1302 `part 1 <http://www-128.ibm.com/developerworks/library/l-prog.html>`__,
    1303 `part 2 <http://www-128.ibm.com/developerworks/library/l-prog2.html>`__, and
    1304 `part 3 <http://www-128.ibm.com/developerworks/linux/library/l-prog3.html>`__,
     1172
     1173`part 1 <http://www.ibm.com/developerworks/linux/library/l-prog/index.html>`__,
     1174`part 2 <http://www.ibm.com/developerworks/linux/library/l-prog2/index.html>`__, and
     1175`part 3 <http://www.ibm.com/developerworks/linux/library/l-prog3/index.html>`__,
    13051176
    13061177
  • python/vendor/current/Doc/howto/index.rst

    r2 r388  
    1414   :maxdepth: 1
    1515
    16    advocacy.rst
     16   pyporting.rst
    1717   cporting.rst
    1818   curses.rst
     19   descriptor.rst
    1920   doanddont.rst
    2021   functional.rst
     22   logging.rst
     23   logging-cookbook.rst
    2124   regex.rst
    2225   sockets.rst
     26   sorting.rst
    2327   unicode.rst
    2428   urllib2.rst
    2529   webservers.rst
     30   argparse.rst
    2631
  • python/vendor/current/Doc/howto/regex.rst

    r2 r388  
    66
    77:Author: A.M. Kuchling <amk@amk.ca>
    8 :Release: 0.05
    98
    109.. TODO:
     
    8382in the rest of this HOWTO. ::
    8483
    85    . ^ $ * + ? { [ ] \ | ( )
     84   . ^ $ * + ? { } [ ] \ | ( )
    8685
    8786The first metacharacters we'll look at are ``[`` and ``]``. They're used for
     
    114113of characters that are often useful, such as the set of digits, the set of
    115114letters, or the set of anything that isn't whitespace.  The following predefined
    116 special sequences are available:
     115special sequences are a subset of those available. The equivalent classes are
     116for byte string patterns. For a complete list of sequences and expanded class
     117definitions for Unicode string patterns, see the last part of
     118:ref:`Regular Expression Syntax <re-syntax>`.
    117119
    118120``\d``
     
    264266   >>> import re
    265267   >>> p = re.compile('ab*')
    266    >>> print p
    267    <_sre.SRE_Pattern object at 80b4150>
     268   >>> p  #doctest: +ELLIPSIS
     269   <_sre.SRE_Pattern object at 0x...>
    268270
    269271:func:`re.compile` also accepts an optional *flags* argument, used to enable
     
    358360
    359361:meth:`match` and :meth:`search` return ``None`` if no match can be found.  If
    360 they're successful, a ``MatchObject`` instance is returned, containing
    361 information about the match: where it starts and ends, the substring it matched,
    362 and more.
     362they're successful, a :ref:`match object <match-objects>` instance is returned,
     363containing information about the match: where it starts and ends, the substring
     364it matched, and more.
    363365
    364366You can learn about this by interactively experimenting with the :mod:`re`
    365367module.  If you have Tkinter available, you may also want to look at
    366 :file:`Tools/scripts/redemo.py`, a demonstration program included with the
     368:source:`Tools/scripts/redemo.py`, a demonstration program included with the
    367369Python distribution.  It allows you to enter REs and strings, and displays
    368370whether the RE matches or fails. :file:`redemo.py` can be quite useful when
     
    377379   >>> import re
    378380   >>> p = re.compile('[a-z]+')
    379    >>> p
    380    <_sre.SRE_Pattern object at 80c3c28>
     381   >>> p  #doctest: +ELLIPSIS
     382   <_sre.SRE_Pattern object at 0x...>
    381383
    382384Now, you can try matching various strings against the RE ``[a-z]+``.  An empty
     
    391393
    392394Now, let's try it on a string that it should match, such as ``tempo``.  In this
    393 case, :meth:`match` will return a :class:`MatchObject`, so you should store the
    394 result in a variable for later use. ::
     395case, :meth:`match` will return a :ref:`match object <match-objects>`, so you
     396should store the result in a variable for later use. ::
    395397
    396398   >>> m = p.match('tempo')
    397    >>> print m
    398    <_sre.SRE_Match object at 80c4f68>
    399 
    400 Now you can query the :class:`MatchObject` for information about the matching
    401 string.   :class:`MatchObject` instances also have several methods and
    402 attributes; the most important ones are:
     399   >>> m  #doctest: +ELLIPSIS
     400   <_sre.SRE_Match object at 0x...>
     401
     402Now you can query the :ref:`match object <match-objects>` for information
     403about the matching string.  :ref:`match object <match-objects>` instances
     404also have several methods and attributes; the most important ones are:
    403405
    404406+------------------+--------------------------------------------+
     
    434436   >>> print p.match('::: message')
    435437   None
    436    >>> m = p.search('::: message') ; print m
    437    <re.MatchObject instance at 80c9650>
     438   >>> m = p.search('::: message'); print m  #doctest: +ELLIPSIS
     439   <_sre.SRE_Match object at 0x...>
    438440   >>> m.group()
    439441   'message'
     
    441443   (4, 11)
    442444
    443 In actual programs, the most common style is to store the :class:`MatchObject`
    444 in a variable, and then check if it was ``None``.  This usually looks like::
     445In actual programs, the most common style is to store the
     446:ref:`match object <match-objects>` in a variable, and then check if it was
     447``None``.  This usually looks like::
    445448
    446449   p = re.compile( ... )
     
    459462
    460463:meth:`findall` has to create the entire list before it can be returned as the
    461 result.  The :meth:`finditer` method returns a sequence of :class:`MatchObject`
    462 instances as an :term:`iterator`. [#]_ ::
     464result.  The :meth:`finditer` method returns a sequence of
     465:ref:`match object <match-objects>` instances as an :term:`iterator`. [#]_ ::
    463466
    464467   >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
    465    >>> iterator
    466    <callable-iterator object at 0x401833ac>
     468   >>> iterator  #doctest: +ELLIPSIS
     469   <callable-iterator object at 0x...>
    467470   >>> for match in iterator:
    468471   ...     print match.span()
     
    481484take the same arguments as the corresponding pattern method, with
    482485the RE string added as the first argument, and still return either ``None`` or a
    483 :class:`MatchObject` instance. ::
     486:ref:`match object <match-objects>` instance. ::
    484487
    485488   >>> print re.match(r'From\s+', 'Fromage amk')
    486489   None
    487    >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')
    488    <re.MatchObject instance at 80c5978>
     490   >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')  #doctest: +ELLIPSIS
     491   <_sre.SRE_Match object at 0x...>
    489492
    490493Under the hood, these functions simply create a pattern object for you
     
    500503the definitions in one place, in a section of code that compiles all the REs
    501504ahead of time.  To take an example from the standard library, here's an extract
    502 from :file:`xmllib.py`::
     505from the deprecated :mod:`xmllib` module::
    503506
    504507   ref = re.compile( ... )
     
    686689   line, the RE to use is ``^From``. ::
    687690
    688       >>> print re.search('^From', 'From Here to Eternity')
    689       <re.MatchObject instance at 80c1520>
     691      >>> print re.search('^From', 'From Here to Eternity')  #doctest: +ELLIPSIS
     692      <_sre.SRE_Match object at 0x...>
    690693      >>> print re.search('^From', 'Reciting From Memory')
    691694      None
     
    698701   or any location followed by a newline character.     ::
    699702
    700       >>> print re.search('}$', '{block}')
    701       <re.MatchObject instance at 80adfa8>
     703      >>> print re.search('}$', '{block}')  #doctest: +ELLIPSIS
     704      <_sre.SRE_Match object at 0x...>
    702705      >>> print re.search('}$', '{block} ')
    703706      None
    704       >>> print re.search('}$', '{block}\n')
    705       <re.MatchObject instance at 80adfa8>
     707      >>> print re.search('}$', '{block}\n')  #doctest: +ELLIPSIS
     708      <_sre.SRE_Match object at 0x...>
    706709
    707710   To match a literal ``'$'``, use ``\$`` or enclose it inside a character class,
     
    727730
    728731      >>> p = re.compile(r'\bclass\b')
    729       >>> print p.search('no class at all')
    730       <re.MatchObject instance at 80c8f28>
     732      >>> print p.search('no class at all')  #doctest: +ELLIPSIS
     733      <_sre.SRE_Match object at 0x...>
    731734      >>> print p.search('the declassified algorithm')
    732735      None
     
    745748      >>> print p.search('no class at all')
    746749      None
    747       >>> print p.search('\b' + 'class' + '\b')
    748       <re.MatchObject instance at 80c3ee0>
     750      >>> print p.search('\b' + 'class' + '\b')  #doctest: +ELLIPSIS
     751      <_sre.SRE_Match object at 0x...>
    749752
    750753   Second, inside a character class, where there's no use for this assertion,
     
    790793to :meth:`group`, :meth:`start`, :meth:`end`, and :meth:`span`.  Groups are
    791794numbered starting with 0.  Group 0 is always present; it's the whole RE, so
    792 :class:`MatchObject` methods all have group 0 as their default argument.  Later
    793 we'll see how to express groups that don't capture the span of text that they
    794 match. ::
     795:ref:`match object <match-objects>` methods all have group 0 as their default
     796argument.  Later we'll see how to express groups that don't capture the span
     797of text that they match. ::
    795798
    796799   >>> p = re.compile('(a)b')
     
    912915``(?P<name>...)``.  *name* is, obviously, the name of the group.  Named groups
    913916also behave exactly like capturing groups, and additionally associate a name
    914 with a group.  The :class:`MatchObject` methods that deal with capturing groups
    915 all accept either integers that refer to the group by number or strings that
    916 contain the desired group's name.  Named groups are still given numbers, so you
    917 can retrieve information about a group in two ways::
     917with a group.  The :ref:`match object <match-objects>` methods that deal with
     918capturing groups all accept either integers that refer to the group by number
     919or strings that contain the desired group's name.  Named groups are still
     920given numbers, so you can retrieve information about a group in two ways::
    918921
    919922   >>> p = re.compile(r'(?P<word>\b\w+\b)')
     
    11791182*replacement* can also be a function, which gives you even more control.  If
    11801183*replacement* is a function, the function is called for every non-overlapping
    1181 occurrence of *pattern*.  On each call, the function is  passed a
    1182 :class:`MatchObject` argument for the match and can use this information to
    1183 compute the desired replacement string and return it.
    1184 
    1185 In the following example, the replacement function translates  decimals into
     1184occurrence of *pattern*.  On each call, the function is passed a
     1185:ref:`match object <match-objects>` argument for the match and can use this
     1186information to compute the desired replacement string and return it.
     1187
     1188In the following example, the replacement function translates decimals into
    11861189hexadecimal::
    11871190
    1188    >>> def hexrepl( match ):
     1191   >>> def hexrepl(match):
    11891192   ...     "Return the hex string for a decimal number"
    1190    ...     value = int( match.group() )
     1193   ...     value = int(match.group())
    11911194   ...     return hex(value)
    11921195   ...
     
    13161319
    13171320
    1318 Not Using re.VERBOSE
     1321Using re.VERBOSE
    13191322--------------------
    13201323
  • python/vendor/current/Doc/howto/sockets.rst

    r2 r388  
     1.. _socket-howto:
     2
    13****************************
    24  Socket Programming HOWTO
     
    1719Sockets
    1820=======
    19 
    20 Sockets are used nearly everywhere, but are one of the most severely
    21 misunderstood technologies around. This is a 10,000 foot overview of sockets.
    22 It's not really a tutorial - you'll still have work to do in getting things
    23 working. It doesn't cover the fine points (and there are a lot of them), but I
    24 hope it will give you enough background to begin using them decently.
    2521
    2622I'm only going to talk about INET sockets, but they account for at least 99% of
     
    4440-------
    4541
    46 Of the various forms of IPC (*Inter Process Communication*), sockets are by far
    47 the most popular.  On any given platform, there are likely to be other forms of
    48 IPC that are faster, but for cross-platform communication, sockets are about the
    49 only game in town.
     42Of the various forms of :abbr:`IPC (Inter Process Communication)`,
     43sockets are by far the most popular.  On any given platform, there are
     44likely to be other forms of IPC that are faster, but for
     45cross-platform communication, sockets are about the only game in town.
    5046
    5147They were invented in Berkeley as part of the BSD flavor of Unix. They spread
     
    6864   s.connect(("www.mcmillan-inc.com", 80))
    6965
    70 When the ``connect`` completes, the socket ``s`` can now be used to send in a
    71 request for the text of this page. The same socket will read the reply, and then
    72 be destroyed. That's right - destroyed. Client sockets are normally only used
    73 for one exchange (or a small set of sequential exchanges).
     66When the ``connect`` completes, the socket ``s`` can be used to send
     67in a request for the text of the page. The same socket will read the
     68reply, and then be destroyed. That's right, destroyed. Client sockets
     69are normally only used for one exchange (or a small set of sequential
     70exchanges).
    7471
    7572What happens in the web server is a bit more complex. First, the web server
    76 creates a "server socket". ::
     73creates a "server socket"::
    7774
    7875   #create an INET, STREAMing socket
     
    8683
    8784A couple things to notice: we used ``socket.gethostname()`` so that the socket
    88 would be visible to the outside world. If we had used ``s.bind(('', 80))`` or
    89 ``s.bind(('localhost', 80))`` or ``s.bind(('127.0.0.1', 80))`` we would still
    90 have a "server" socket, but one that was only visible within the same machine.
     85would be visible to the outside world.  If we had used ``s.bind(('localhost',
     8680))`` or ``s.bind(('127.0.0.1', 80))`` we would still have a "server" socket,
     87but one that was only visible within the same machine.  ``s.bind(('', 80))``
     88specifies that the socket is reachable by any address the machine happens to
     89have.
    9190
    9291A second thing to note: low number ports are usually reserved for "well known"
     
    9897connections. If the rest of the code is written properly, that should be plenty.
    9998
    100 OK, now we have a "server" socket, listening on port 80. Now we enter the
     99Now that we have a "server" socket, listening on port 80, we can enter the
    101100mainloop of the web server::
    102101
     
    147146Now there are two sets of verbs to use for communication. You can use ``send``
    148147and ``recv``, or you can transform your client socket into a file-like beast and
    149 use ``read`` and ``write``. The latter is the way Java presents their sockets.
     148use ``read`` and ``write``. The latter is the way Java presents its sockets.
    150149I'm not going to talk about it here, except to warn you that you need to use
    151150``flush`` on sockets. These are buffered "files", and a common mistake is to
     
    154153your output buffer.
    155154
    156 Now we come the major stumbling block of sockets - ``send`` and ``recv`` operate
     155Now we come to the major stumbling block of sockets - ``send`` and ``recv`` operate
    157156on the network buffers. They do not necessarily handle all the bytes you hand
    158157them (or expect from them), because their major focus is handling the network
     
    165164the process of closing) the connection.  You will not receive any more data on
    166165this connection. Ever.  You may be able to send data successfully; I'll talk
    167 about that some on the next page.
     166more about this later.
    168167
    169168A protocol like HTTP uses a socket for only one transfer. The client sends a
    170 request, the reads a reply.  That's it. The socket is discarded. This means that
     169request, then reads a reply.  That's it. The socket is discarded. This means that
    171170a client can detect the end of the reply by receiving 0 bytes.
    172171
    173172But if you plan to reuse your socket for further transfers, you need to realize
    174 that *there is no "EOT" (End of Transfer) on a socket.* I repeat: if a socket
     173that *there is no* :abbr:`EOT (End of Transfer)` *on a socket.* I repeat: if a socket
    175174``send`` or ``recv`` returns after handling 0 bytes, the connection has been
    176175broken.  If the connection has *not* been broken, you may wait on a ``recv``
     
    315314====================
    316315
    317 If you've understood the preceeding, you already know most of what you need to
     316If you've understood the preceding, you already know most of what you need to
    318317know about the mechanics of using sockets. You'll still use the same calls, in
    319318much the same ways. It's just that, if you do it right, your app will be almost
     
    338337In C, coding ``select`` is fairly complex. In Python, it's a piece of cake, but
    339338it's close enough to the C version that if you understand ``select`` in Python,
    340 you'll have little trouble with it in C. ::
     339you'll have little trouble with it in C::
    341340
    342341   ready_to_read, ready_to_write, in_error = \
     
    355354reason to do otherwise.
    356355
    357 In return, you will get three lists. They have the sockets that are actually
     356In return, you will get three lists. They contain the sockets that are actually
    358357readable, writable and in error. Each of these lists is a subset (possibly
    359 empty) of the corresponding list you passed in. And if you put a socket in more
    360 than one input list, it will only be (at most) in one output list.
     358empty) of the corresponding list you passed in.
    361359
    362360If a socket is in the output readable list, you can be
  • python/vendor/current/Doc/howto/unicode.rst

    r2 r388  
    33*****************
    44
    5 :Release: 1.02
    6 
    7 This HOWTO discusses Python's support for Unicode, and explains various problems
    8 that people commonly encounter when trying to work with Unicode.
     5:Release: 1.03
     6
     7This HOWTO discusses Python 2.x's support for Unicode, and explains
     8various problems that people commonly encounter when trying to work
     9with Unicode.  For the Python 3 version, see
     10<http://docs.python.org/py3k/howto/unicode.html>.
    911
    1012Introduction to Unicode
     
    145147   handle content with embedded zero bytes.
    146148
    147 Generally people don't use this encoding, instead choosing other encodings that
    148 are more efficient and convenient.
     149Generally people don't use this encoding, instead choosing other
     150encodings that are more efficient and convenient.  UTF-8 is probably
     151the most commonly supported encoding; it will be discussed below.
    149152
    150153Encodings don't have to handle every possible Unicode character, and most
     
    223226
    224227
    225 Python's Unicode Support
    226 ========================
     228Python 2.x's Unicode Support
     229============================
    227230
    228231Now that you've learned the rudiments of Unicode, we can look at Python's
     
    251254    >>> type(s)
    252255    <type 'unicode'>
    253     >>> unicode('abcdef' + chr(255))
     256    >>> unicode('abcdef' + chr(255))    #doctest: +NORMALIZE_WHITESPACE
    254257    Traceback (most recent call last):
    255       File "<stdin>", line 1, in ?
     258    ...
    256259    UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 6:
    257                         ordinal not in range(128)
     260    ordinal not in range(128)
    258261
    259262The ``errors`` argument specifies the response when the input string can't be
     
    263266Unicode result).  The following examples show the differences::
    264267
    265     >>> unicode('\x80abc', errors='strict')
     268    >>> unicode('\x80abc', errors='strict')     #doctest: +NORMALIZE_WHITESPACE
    266269    Traceback (most recent call last):
    267       File "<stdin>", line 1, in ?
     270        ...
    268271    UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0:
    269                         ordinal not in range(128)
     272    ordinal not in range(128)
    270273    >>> unicode('\x80abc', errors='replace')
    271274    u'\ufffdabc'
     
    273276    u'abc'
    274277
    275 Encodings are specified as strings containing the encoding's name.  Python 2.4
     278Encodings are specified as strings containing the encoding's name.  Python 2.7
    276279comes with roughly 100 different encodings; see the Python Library Reference at
    277280:ref:`standard-encodings` for a list.  Some encodings
     
    310313than 127 will cause an exception::
    311314
    312     >>> s.find('Was\x9f')
     315    >>> s.find('Was\x9f')                   #doctest: +NORMALIZE_WHITESPACE
    313316    Traceback (most recent call last):
    314       File "<stdin>", line 1, in ?
    315     UnicodeDecodeError: 'ascii' codec can't decode byte 0x9f in position 3: ordinal not in range(128)
     317        ...
     318    UnicodeDecodeError: 'ascii' codec can't decode byte 0x9f in position 3:
     319    ordinal not in range(128)
    316320    >>> s.find(u'Was\x9f')
    317321    -1
     
    331335    >>> u.encode('utf-8')
    332336    '\xea\x80\x80abcd\xde\xb4'
    333     >>> u.encode('ascii')
     337    >>> u.encode('ascii')                       #doctest: +NORMALIZE_WHITESPACE
    334338    Traceback (most recent call last):
    335       File "<stdin>", line 1, in ?
    336     UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in position 0: ordinal not in range(128)
     339        ...
     340    UnicodeEncodeError: 'ascii' codec can't encode character u'\ua000' in
     341    position 0: ordinal not in range(128)
    337342    >>> u.encode('ascii', 'ignore')
    338343    'abcd'
     
    382387
    383388    >>> s = u"a\xac\u1234\u20ac\U00008000"
    384                ^^^^ two-digit hex escape
    385                    ^^^^^^ four-digit Unicode escape
    386                                ^^^^^^^^^^ eight-digit Unicode escape
     389    ... #      ^^^^ two-digit hex escape
     390    ... #          ^^^^^^ four-digit Unicode escape
     391    ... #                      ^^^^^^^^^^ eight-digit Unicode escape
    387392    >>> for c in s:  print ord(c),
    388393    ...
     
    428433When you run it with Python 2.4, it will output the following warning::
    429434
    430     amk:~$ python p263.py
     435    amk:~$ python2.4 p263.py
    431436    sys:1: DeprecationWarning: Non-ASCII character '\xe9'
    432437         in file p263.py on line 2, but no encoding declared;
    433438         see http://www.python.org/peps/pep-0263.html for details
     439
     440Python 2.5 and higher are stricter and will produce a syntax error::
     441
     442    amk:~$ python2.5 p263.py
     443    File "/tmp/p263.py", line 2
     444    SyntaxError: Non-ASCII character '\xc3' in file /tmp/p263.py
     445      on line 2, but no encoding declared; see
     446      http://www.python.org/peps/pep-0263.html for details
    434447
    435448
     
    473486"Number, other", ``'Mn'`` is "Mark, nonspacing", and ``'So'`` is "Symbol,
    474487other".  See
    475 <http://unicode.org/Public/5.1.0/ucd/UCD.html#General_Category_Values> for a
     488<http://www.unicode.org/reports/tr44/#General_Category_Values> for a
    476489list of category codes.
    477490
     
    694707Version 1.02: posted August 16 2005.  Corrects factual errors.
    695708
    696 
     709Version 1.03: posted June 20 2010.  Notes that Python 3.x is not covered,
     710and that the HOWTO only covers 2.x.
     711
     712
     713.. comment Describe Python 3.x support (new section? new document?)
    697714.. comment Additional topic: building Python w/ UCS2 or UCS4 support
    698715.. comment Describe obscure -U switch somewhere?
  • python/vendor/current/Doc/howto/urllib2.rst

    r2 r388  
    135135    >>> data['language'] = 'Python'
    136136    >>> url_values = urllib.urlencode(data)
    137     >>> print url_values
     137    >>> print url_values  # The order may differ. #doctest: +SKIP
    138138    name=Somebody+Here&language=Python&location=Northampton
    139139    >>> url = 'http://www.example.com/example.cgi'
    140140    >>> full_url = url + '?' + url_values
    141     >>> data = urllib2.open(full_url)
     141    >>> data = urllib2.urlopen(full_url)
    142142
    143143Notice that the full URL is created by adding a ``?`` to the URL, followed by
     
    202202    >>> req = urllib2.Request('http://www.pretend_server.org')
    203203    >>> try: urllib2.urlopen(req)
    204     >>> except URLError, e:
    205     >>>    print e.reason
    206     >>>
     204    ... except URLError as e:
     205    ...    print e.reason   #doctest: +SKIP
     206    ...
    207207    (4, 'getaddrinfo failed')
    208208
     
    310310    >>> req = urllib2.Request('http://www.python.org/fish.html')
    311311    >>> try:
    312     >>>     urllib2.urlopen(req)
    313     >>> except HTTPError, e:
    314     >>>     print e.code
    315     >>>     print e.read()
    316     >>>
     312    ...     urllib2.urlopen(req)
     313    ... except urllib2.HTTPError as e:
     314    ...     print e.code
     315    ...     print e.read() #doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
     316    ...
    317317    404
    318     <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    319         "http://www.w3.org/TR/html4/loose.dtd">
    320     <?xml-stylesheet href="./css/ht2html.css"
    321         type="text/css"?>
    322     <html><head><title>Error 404: File Not Found</title>
    323     ...... etc...
     318    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     319    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     320    ...
     321    <title>Page Not Found</title>
     322    ...
     323
    324324
    325325Wrapping it Up
     
    339339    try:
    340340        response = urlopen(req)
    341     except HTTPError, e:
     341    except HTTPError as e:
    342342        print 'The server couldn\'t fulfill the request.'
    343343        print 'Error code: ', e.code
    344     except URLError, e:
     344    except URLError as e:
    345345        print 'We failed to reach a server.'
    346346        print 'Reason: ', e.reason
     
    363363    try:
    364364        response = urlopen(req)
    365     except URLError, e:
     365    except URLError as e:
    366366        if hasattr(e, 'reason'):
    367367            print 'We failed to reach a server.'
     
    440440When authentication is required, the server sends a header (as well as the 401
    441441error code) requesting authentication.  This specifies the authentication scheme
    442 and a 'realm'. The header looks like : ``Www-authenticate: SCHEME
     442and a 'realm'. The header looks like : ``WWW-Authenticate: SCHEME
    443443realm="REALM"``.
    444444
    445445e.g. ::
    446446
    447     Www-authenticate: Basic realm="cPanel Users"
     447    WWW-Authenticate: Basic realm="cPanel Users"
    448448
    449449
     
    490490    In the above example we only supplied our ``HTTPBasicAuthHandler`` to
    491491    ``build_opener``. By default openers have the handlers for normal situations
    492     -- ``ProxyHandler``, ``UnknownHandler``, ``HTTPHandler``,
     492    -- ``ProxyHandler`` (if a proxy setting such as an :envvar:`http_proxy`
     493    environment variable is set), ``UnknownHandler``, ``HTTPHandler``,
    493494    ``HTTPDefaultErrorHandler``, ``HTTPRedirectHandler``, ``FTPHandler``,
    494495    ``FileHandler``, ``HTTPErrorProcessor``.
     
    507508
    508509**urllib2** will auto-detect your proxy settings and use those. This is through
    509 the ``ProxyHandler`` which is part of the normal handler chain. Normally that's
    510 a good thing, but there are occasions when it may not be helpful [#]_. One way
    511 to do this is to setup our own ``ProxyHandler``, with no proxies defined. This
    512 is done using similar steps to setting up a `Basic Authentication`_ handler : ::
     510the ``ProxyHandler``, which is part of the normal handler chain when a proxy
     511setting is detected.  Normally that's a good thing, but there are occasions
     512when it may not be helpful [#]_. One way to do this is to setup our own
     513``ProxyHandler``, with no proxies defined. This is done using similar steps to
     514setting up a `Basic Authentication`_ handler : ::
    513515
    514516    >>> proxy_support = urllib2.ProxyHandler({})
  • python/vendor/current/Doc/howto/webservers.rst

    r2 r388  
    77.. topic:: Abstract
    88
    9    This document shows how Python fits into the web.  It presents some ways on
    10    how to integrate Python with the web server and general practices useful for
     9   This document shows how Python fits into the web.  It presents some ways
     10   to integrate Python with a web server, and general practices useful for
    1111   developing web sites.
    1212
    1313
    14 Programming for the Web has become a hot topic since the raise of the "Web 2.0",
     14Programming for the Web has become a hot topic since the rise of "Web 2.0",
    1515which focuses on user-generated content on web sites.  It has always been
    1616possible to use Python for creating web sites, but it was a rather tedious task.
    17 Therefore, many so-called "frameworks" and helper tools were created to help
    18 developers creating sites faster and these sites being more robust.  This HOWTO
    19 describes some of the methods used to combine Python with a web server to create
    20 dynamic content.  It is not meant as a general introduction as this topic is far
    21 too broad to be covered in one single document.  However, a short overview of
    22 the most popular libraries is provided.
    23 
    24 .. seealso::
    25 
    26    While this HOWTO tries to give an overview over Python in the Web, it cannot
    27    always be as up to date as desired.  Web development in Python is moving
    28    forward rapidly, so the wiki page on `Web Programming
    29    <http://wiki.python.org/moin/WebProgramming>`_ might be more in sync with
     17Therefore, many frameworks and helper tools have been created to assist
     18developers in creating faster and more robust sites.  This HOWTO describes
     19some of the methods used to combine Python with a web server to create
     20dynamic content.  It is not meant as a complete introduction, as this topic is
     21far too broad to be covered in one single document.  However, a short overview
     22of the most popular libraries is provided.
     23
     24.. seealso::
     25
     26   While this HOWTO tries to give an overview of Python in the web, it cannot
     27   always be as up to date as desired.  Web development in Python is rapidly
     28   moving forward, so the wiki page on `Web Programming
     29   <http://wiki.python.org/moin/WebProgramming>`_ may be more in sync with
    3030   recent development.
    3131
    3232
    33 The low-level view
     33The Low-Level View
    3434==================
    3535
    36 .. .. image:: http.png
    37 
    38 When a user enters a web site, his browser makes a connection to the site's
    39 webserver (this is called the *request*).  The server looks up the file in the
     36When a user enters a web site, their browser makes a connection to the site's
     37web server (this is called the *request*).  The server looks up the file in the
    4038file system and sends it back to the user's browser, which displays it (this is
    41 the *response*).  This is roughly how the unterlying protocol, HTTP works.
    42 
    43 Now, dynamic web sites are not files in the file system, but rather programs
    44 which are run by the web server when a request comes in.  They can do all sorts
    45 of useful things, like display the postings of a bulletin board, show your
    46 mails, configurate software or just display the current time.  These programs
    47 can be written in about any programming language the server supports, so it is
    48 easy to use Python for creating dynamic web sites.
    49 
    50 As most of HTTP servers are written in C or C++, they cannot execute Python code
    51 in a simple way -- a bridge is needed between the server and the program.  These
    52 bridges or rather interfaces define how programs interact with the server.  In
    53 the past there have been numerous attempts to create the best possible
    54 interface, but there are only a few worth mentioning.
    55 
    56 Not every web server supports every interface.  Many web servers do support only
    57 old, now-obsolete interfaces.  But they can often be extended using some
    58 third-party modules to support new interfaces.
     39the *response*).  This is roughly how the underlying protocol, HTTP, works.
     40
     41Dynamic web sites are not based on files in the file system, but rather on
     42programs which are run by the web server when a request comes in, and which
     43*generate* the content that is returned to the user.  They can do all sorts of
     44useful things, like display the postings of a bulletin board, show your email,
     45configure software, or just display the current time.  These programs can be
     46written in any programming language the server supports.  Since most servers
     47support Python, it is easy to use Python to create dynamic web sites.
     48
     49Most HTTP servers are written in C or C++, so they cannot execute Python code
     50directly -- a bridge is needed between the server and the program.  These
     51bridges, or rather interfaces, define how programs interact with the server.
     52There have been numerous attempts to create the best possible interface, but
     53there are only a few worth mentioning.
     54
     55Not every web server supports every interface.  Many web servers only support
     56old, now-obsolete interfaces; however, they can often be extended using
     57third-party modules to support newer ones.
    5958
    6059
     
    6261------------------------
    6362
    64 This interface is the oldest one, supported by nearly every web server out of
    65 the box.  Programs using CGI to communicate with their web server need to be
    66 started by the server for every request.  So, every request starts a new Python
    67 interpreter -- which takes some time to start up -- thus making the whole
    68 interface only usable for low load situations.
    69 
    70 The upside of CGI is that it is simple -- writing a program which uses CGI is a
    71 matter of about three lines of code.  But this simplicity comes at a price: it
    72 does very few things to help the developer.
    73 
    74 Writing CGI programs, while still possible, is not recommended anymore.  With
    75 WSGI (more on that later) it is possible to write programs that emulate CGI, so
    76 they can be run as CGI if no better option is available.
     63This interface, most commonly referred to as "CGI", is the oldest, and is
     64supported by nearly every web server out of the box.  Programs using CGI to
     65communicate with their web server need to be started by the server for every
     66request.  So, every request starts a new Python interpreter -- which takes some
     67time to start up -- thus making the whole interface only usable for low load
     68situations.
     69
     70The upside of CGI is that it is simple -- writing a Python program which uses
     71CGI is a matter of about three lines of code.  This simplicity comes at a
     72price: it does very few things to help the developer.
     73
     74Writing CGI programs, while still possible, is no longer recommended.  With
     75:ref:`WSGI <WSGI>`, a topic covered later in this document, it is possible to write
     76programs that emulate CGI, so they can be run as CGI if no better option is
     77available.
    7778
    7879.. seealso::
     
    8283
    8384   * :mod:`cgi` -- Handling of user input in CGI scripts
    84    * :mod:`cgitb` -- Displays nice tracebacks when errors happen in of CGI
     85   * :mod:`cgitb` -- Displays nice tracebacks when errors happen in CGI
    8586     applications, instead of presenting a "500 Internal Server Error" message
    8687
     
    108109    print "Hello World!"
    109110
    110 You need to write this code into a file with a ``.py`` or ``.cgi`` extension,
    111 this depends on your web server configuration.  Depending on your web server
    112 configuration, this file may also need to be in a ``cgi-bin`` folder, for
    113 security reasons.
     111Depending on your web server configuration, you may need to save this code with
     112a ``.py`` or ``.cgi`` extension.  Additionally, this file may also need to be
     113in a ``cgi-bin`` folder, for security reasons.
    114114
    115115You might wonder what the ``cgitb`` line is about.  This line makes it possible
    116116to display a nice traceback instead of just crashing and displaying an "Internal
    117117Server Error" in the user's browser.  This is useful for debugging, but it might
    118 risk exposing some confident data to the user.  Don't use it when the script is
    119 ready for production use.  Still, you should *always* catch exceptions, and
     118risk exposing some confidential data to the user.  You should not use ``cgitb``
     119in production code for this reason.  You should *always* catch exceptions, and
    120120display proper error pages -- end-users don't like to see nondescript "Internal
    121121Server Errors" in their browsers.
     
    126126
    127127If you don't have your own web server, this does not apply to you.  You can
    128 check whether if works as-is and if not you need to talk to the administrator of
    129 your web server anyway. If it is a big hoster, you can try filing a ticket
    130 asking for Python support.
    131 
    132 If you're your own administrator or want to install it for testing purposes on
    133 your own computers, you have to configure it by yourself.  There is no one and
    134 single way on how to configure CGI, as there are many web servers with different
    135 configuration options.  The currently most widely used free web server is
    136 `Apache HTTPd <http://httpd.apache.org/>`_, Apache for short -- this is the one
    137 that most people use, it can be easily installed on nearly every system using
    138 the systems' package management.  But `lighttpd <http://www.lighttpd.net>`_ has
    139 been gaining attention since some time and is said to have a better performance.
    140 On many systems this server can also be installed using the package management,
    141 so manually compiling the web server is never needed.
    142 
    143 * On Apache you can take a look into the `Dynamic Content with CGI
     128check whether it works as-is, and if not you will need to talk to the
     129administrator of your web server. If it is a big host, you can try filing a
     130ticket asking for Python support.
     131
     132If you are your own administrator or want to set up CGI for testing purposes on
     133your own computers, you have to configure it by yourself.  There is no single
     134way to configure CGI, as there are many web servers with different
     135configuration options.  Currently the most widely used free web server is
     136`Apache HTTPd <http://httpd.apache.org/>`_, or Apache for short. Apache can be
     137easily installed on nearly every system using the system's package management
     138tool.  `lighttpd <http://www.lighttpd.net>`_ is another alternative and is
     139said to have better performance.  On many systems this server can also be
     140installed using the package management tool, so manually compiling the web
     141server may not be needed.
     142
     143* On Apache you can take a look at the `Dynamic Content with CGI
    144144  <http://httpd.apache.org/docs/2.2/howto/cgi.html>`_ tutorial, where everything
    145145  is described.  Most of the time it is enough just to set ``+ExecCGI``.  The
    146146  tutorial also describes the most common gotchas that might arise.
     147
    147148* On lighttpd you need to use the `CGI module
    148   <http://trac.lighttpd.net/trac/wiki/Docs%3AModCGI>`_ which can be configured
     149  <http://redmine.lighttpd.net/wiki/lighttpd/Docs:ModCGI>`_\ , which can be configured
    149150  in a straightforward way.  It boils down to setting ``cgi.assign`` properly.
    150151
     
    153154^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    154155
    155 Trying to use CGI sometimes leads to small annoyances that one might experience
    156 while trying to get these scripts to run.  Sometimes it happens that a seemingly
    157 correct script does not work as expected, which is caused by some small hidden
    158 reason that's difficult to spot.
    159 
    160 Some of these reasons are:
    161 
    162 * The Python script is not marked executable.  When CGI scripts are not
    163   executable most of the web servers will let the user download it, instead of
     156Using CGI sometimes leads to small annoyances while trying to get these
     157scripts to run.  Sometimes a seemingly correct script does not work as
     158expected, the cause being some small hidden problem that's difficult to spot.
     159
     160Some of these potential problems are:
     161
     162* The Python script is not marked as executable.  When CGI scripts are not
     163  executable most web servers will let the user download it, instead of
    164164  running it and sending the output to the user.  For CGI scripts to run
    165   properly the ``+x`` bit needs to be set.  Using ``chmod a+x your_script.py``
    166   might already solve the problem.
    167 * The line endings must be of Unix-type.  This is important because the web
    168   server checks the first line of the script (called shebang) and tries to run
    169   the program specified there.  It gets easily confused by Windows line endings
    170   (Carriage Return & Line Feed, also called CRLF), so you have to convert the
    171   file to Unix line endings (only Line Feed, LF).  This can be done
    172   automatically by uploading the file via FTP in text mode instead of binary
    173   mode, but the preferred way is just telling your editor to save the files with
    174   Unix line endings.  Most proper editors support this.
    175 * Your web server must be able to read the file, you need to make sure the
    176   permissions are fine.  Often the server runs as user and group ``www-data``,
    177   so it might be worth a try to change the file ownership or making the file
    178   world readable by using ``chmod a+r your_script.py``.
    179 * The webserver must be able to know that the file you're trying to access is a
    180   CGI script.  Check the configuration of your web server, maybe there is some
    181   mistake.
    182 * The path to the interpreter in the shebang (``#!/usr/bin/env python``) must be
    183   currect.  This line calls ``/usr/bin/env`` to find Python, but it'll fail if
    184   there is no ``/usr/bin/env``.  If you know where your Python is installed, you
    185   can also use that path.  The commands ``whereis python`` and ``type -p
    186   python`` might also help to find where it is installed.  Once this is known,
    187   the shebang line can be changed accordingly: ``#!/usr/bin/python``.
     165  properly on Unix-like operating systems, the ``+x`` bit needs to be set.
     166  Using ``chmod a+x your_script.py`` may solve this problem.
     167
     168* On a Unix-like system, The line endings in the program file must be Unix
     169  style line endings.  This is important because the web server checks the
     170  first line of the script (called shebang) and tries to run the program
     171  specified there.  It gets easily confused by Windows line endings (Carriage
     172  Return & Line Feed, also called CRLF), so you have to convert the file to
     173  Unix line endings (only Line Feed, LF).  This can be done automatically by
     174  uploading the file via FTP in text mode instead of binary mode, but the
     175  preferred way is just telling your editor to save the files with Unix line
     176  endings.  Most editors support this.
     177
     178* Your web server must be able to read the file, and you need to make sure the
     179  permissions are correct.  On unix-like systems, the server often runs as user
     180  and group ``www-data``, so it might be worth a try to change the file
     181  ownership, or making the file world readable by using ``chmod a+r
     182  your_script.py``.
     183
     184* The web server must know that the file you're trying to access is a CGI script.
     185  Check the configuration of your web server, as it may be configured
     186  to expect a specific file extension for CGI scripts.
     187
     188* On Unix-like systems, the path to the interpreter in the shebang
     189  (``#!/usr/bin/env python``) must be correct.  This line calls
     190  ``/usr/bin/env`` to find Python, but it will fail if there is no
     191  ``/usr/bin/env``, or if Python is not in the web server's path.  If you know
     192  where your Python is installed, you can also use that full path.  The
     193  commands ``whereis python`` and ``type -p python`` could help you find
     194  where it is installed.  Once you know the path, you can change the shebang
     195  accordingly: ``#!/usr/bin/python``.
     196
    188197* The file must not contain a BOM (Byte Order Mark). The BOM is meant for
    189   determining the byte order of UTF-16 encodings, but some editors write this
    190   also into UTF-8 files.  The BOM interferes with the shebang line, so be sure
    191   to tell your editor not to write the BOM.
    192 * :ref:`mod-python` might be making problems.  mod_python is able to handle CGI
    193   scripts by itself, but it can also be a source for problems.  Be sure you
    194   disable it.
     198  determining the byte order of UTF-16 and UTF-32 encodings, but some editors
     199  write this also into UTF-8 files.  The BOM interferes with the shebang line,
     200  so be sure to tell your editor not to write the BOM.
     201
     202* If the web server is using :ref:`mod-python`, ``mod_python`` may be having
     203  problems.  ``mod_python`` is able to handle CGI scripts by itself, but it can
     204  also be a source of issues.
    195205
    196206
     
    201211
    202212People coming from PHP often find it hard to grasp how to use Python in the web.
    203 Their first thought is mostly `mod_python <http://www.modpython.org/>`_ because
    204 they think that this is the equivalent to ``mod_php``.  Actually it is not
    205 really.  It does embed the interpreter into the Apache process, thus speeding up
    206 requests by not having to start a Python interpreter every request.  On the
    207 other hand, it is by far not "Python intermixed with HTML" as PHP often does.
    208 The Python equivalent of that is a template engine.  mod_python itself is much
    209 more powerful and gives more access to Apache internals.  It can emulate CGI, it
    210 can work an a "Python Server Pages" mode similar to JSP which is "HTML
    211 intermangled with Python" and it has a "Publisher" which destignates one file to
    212 accept all requests and decide on what to do then.
    213 
    214 But mod_python has some problems.  Unlike the PHP interpreter the Python
    215 interpreter uses caching when executing files, so when changing a file the whole
    216 web server needs to be re-started to update.  Another problem ist the basic
    217 concept -- Apache starts some child processes to handle the requests and
    218 unfortunately every child process needs to load the whole Python interpreter
    219 even if it does not use it.  This makes the whole web server slower.  Another
    220 problem is that as mod_python is linked against a specific version of
    221 ``libpython``, it is not possible to switch from an older version to a newer
    222 (e.g. 2.4 to 2.5) without recompiling mod_python.  mod_python is also bound to
    223 the Apache web server, so programs written for mod_python cannot easily run on
    224 other web servers.
    225 
    226 These are the reasons why mod_python should be avoided when writing new
    227 programs.  In some circumstances it might be still a good idea to use mod_python
    228 for deployment, but WSGI makes it possible to run WSGI programs under mod_python
    229 as well.
     213Their first thought is mostly `mod_python <http://www.modpython.org/>`_\ ,
     214because they think that this is the equivalent to ``mod_php``.  Actually, there
     215are many differences.  What ``mod_python`` does is embed the interpreter into
     216the Apache process, thus speeding up requests by not having to start a Python
     217interpreter for each request.  On the other hand, it is not "Python intermixed
     218with HTML" in the way that PHP is often intermixed with HTML. The Python
     219equivalent of that is a template engine.  ``mod_python`` itself is much more
     220powerful and provides more access to Apache internals.  It can emulate CGI,
     221work in a "Python Server Pages" mode (similar to JSP) which is "HTML
     222intermingled with Python", and it has a "Publisher" which designates one file
     223to accept all requests and decide what to do with them.
     224
     225``mod_python`` does have some problems.  Unlike the PHP interpreter, the Python
     226interpreter uses caching when executing files, so changes to a file will
     227require the web server to be restarted.  Another problem is the basic concept
     228-- Apache starts child processes to handle the requests, and unfortunately
     229every child process needs to load the whole Python interpreter even if it does
     230not use it.  This makes the whole web server slower.  Another problem is that,
     231because ``mod_python`` is linked against a specific version of ``libpython``,
     232it is not possible to switch from an older version to a newer (e.g. 2.4 to 2.5)
     233without recompiling ``mod_python``.  ``mod_python`` is also bound to the Apache
     234web server, so programs written for ``mod_python`` cannot easily run on other
     235web servers.
     236
     237These are the reasons why ``mod_python`` should be avoided when writing new
     238programs.  In some circumstances it still might be a good idea to use
     239``mod_python`` for deployment, but WSGI makes it possible to run WSGI programs
     240under ``mod_python`` as well.
    230241
    231242
     
    235246FastCGI and SCGI try to solve the performance problem of CGI in another way.
    236247Instead of embedding the interpreter into the web server, they create
    237 long-running processes which run in the background. There still is some module
    238 in the web server which makes it possible for the web server to "speak" with the
    239 background process.  As the background process is independent from the server,
    240 it can be written in any language of course also in Python.  The language just
    241 needs to have a library which handles the communication with the web server.
     248long-running background processes. There is still a module in the web server
     249which makes it possible for the web server to "speak" with the background
     250process.  As the background process is independent of the server, it can be
     251written in any language, including Python.  The language just needs to have a
     252library which handles the communication with the webserver.
    242253
    243254The difference between FastCGI and SCGI is very small, as SCGI is essentially
    244 just a "simpler FastCGI".  But as the web server support for SCGI is limited
     255just a "simpler FastCGI".  As the web server support for SCGI is limited,
    245256most people use FastCGI instead, which works the same way.  Almost everything
    246 that applies to SCGI also applies to FastCGI as well, so we'll only write about
     257that applies to SCGI also applies to FastCGI as well, so we'll only cover
    247258the latter.
    248259
    249 These days, FastCGI is never used directly.  Just like ``mod_python`` it is only
     260These days, FastCGI is never used directly.  Just like ``mod_python``, it is only
    250261used for the deployment of WSGI applications.
    251262
     
    254265   * `FastCGI, SCGI, and Apache: Background and Future
    255266     <http://www.vmunix.com/mark/blog/archives/2006/01/02/fastcgi-scgi-and-apache-background-and-future/>`_
    256      is a discussion on why the concept of FastCGI and SCGI is better that that
     267     is a discussion on why the concept of FastCGI and SCGI is better than that
    257268     of mod_python.
    258269
     
    261272^^^^^^^^^^^^^^^^^^
    262273
    263 Depending on the web server you need to have a special module.
    264 
    265 * Apache has both `mod_fastcgi <http://www.fastcgi.com/>`_ and `mod_fcgid
    266   <http://fastcgi.coremail.cn/>`_.  ``mod_fastcgi`` is the original one, but it
    267   has some licensing issues that's why it is sometimes considered non-free.
    268   ``mod_fcgid`` is a smaller, compatible alternative. One of these modules needs
     274Each web server requires a specific module.
     275
     276* Apache has both `mod_fastcgi <http://www.fastcgi.com/drupal/>`_ and `mod_fcgid
     277  <http://httpd.apache.org/mod_fcgid/>`_.  ``mod_fastcgi`` is the original one, but it
     278  has some licensing issues, which is why it is sometimes considered non-free.
     279  ``mod_fcgid`` is a smaller, compatible alternative.  One of these modules needs
    269280  to be loaded by Apache.
     281
    270282* lighttpd ships its own `FastCGI module
    271   <http://trac.lighttpd.net/trac/wiki/Docs%3AModFastCGI>`_ as well as an `SCGI
    272   module <http://trac.lighttpd.net/trac/wiki/Docs%3AModSCGI>`_.
    273 * nginx also supports `FastCGI <http://wiki.nginx.org/NginxSimplePythonFCGI>`_.
     283  <http://redmine.lighttpd.net/wiki/lighttpd/Docs:ModFastCGI>`_ as well as an
     284  `SCGI module <http://redmine.lighttpd.net/wiki/lighttpd/Docs:ModSCGI>`_.
     285
     286* `nginx <http://nginx.org/>`_ also supports `FastCGI
     287  <http://wiki.nginx.org/NginxSimplePythonFCGI>`_.
    274288
    275289Once you have installed and configured the module, you can test it with the
     
    301315
    302316   There is some documentation on `setting up Django with FastCGI
    303    <http://www.djangoproject.com/documentation/fastcgi/>`_, most of which can be
    304    reused for other WSGI-compliant frameworks and libraries.  Only the
    305    ``manage.py`` part has to be changed, the example used here can be used
    306    instead. Django does more or less the exact same thing.
     317   <http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/>`_, most of
     318   which can be reused for other WSGI-compliant frameworks and libraries.
     319   Only the ``manage.py`` part has to be changed, the example used here can be
     320   used instead. Django does more or less the exact same thing.
    307321
    308322
     
    310324--------
    311325
    312 `mod_wsgi <http://www.modwsgi.org/>`_ is an attempt to get rid of the low level
    313 gateways.  As FastCGI, SCGI, mod_python are mostly used to deploy WSGI
    314 applications anyway, mod_wsgi was started to directly embed WSGI aplications
    315 into the Apache web server.  The benefit from this approach is that WSGI
    316 applications can be deployed much easier as is is specially designed to host
    317 WSGI applications -- unlike the other low level methods which have glue code to
    318 host WSGI applications (like flup which was mentioned before).  The downside is
    319 that mod_wsgi is limited to the Apache web server, other servers would need
     326`mod_wsgi <http://code.google.com/p/modwsgi/>`_ is an attempt to get rid of the
     327low level gateways.  Given that FastCGI, SCGI, and mod_python are mostly used to
     328deploy WSGI applications, mod_wsgi was started to directly embed WSGI applications
     329into the Apache web server. mod_wsgi is specifically designed to host WSGI
     330applications.  It makes the deployment of WSGI applications much easier than
     331deployment using other low level methods, which need glue code.  The downside
     332is that mod_wsgi is limited to the Apache web server; other servers would need
    320333their own implementations of mod_wsgi.
    321334
    322 It supports two modes: the embedded mode in which it integrates with the Apache
    323 process and the daemon mode which is more FastCGI-like.  Contrary to FastCGI,
    324 mod_wsgi handles the worker-processes by itself which makes administration
     335mod_wsgi supports two modes: embedded mode, in which it integrates with the
     336Apache process, and daemon mode, which is more FastCGI-like.  Unlike FastCGI,
     337mod_wsgi handles the worker-processes by itself, which makes administration
    325338easier.
    326339
     
    331344===============
    332345
    333 WSGI was already mentioned several times so it has to be something important.
    334 In fact it really is, so now it's time to explain.
    335 
    336 The *Web Server Gateway Interface*, :pep:`333` or WSGI for short is currently
    337 the best possible way to Python web programming.  While it is great for
    338 programmers writing frameworks, the normal person does not need to get in direct
    339 contact with it.  But when choosing a framework for web development it is a good
    340 idea to take one which supports WSGI.
    341 
    342 The big profit from WSGI is the unification.  When your program is compatible
    343 with WSGI -- that means that your framework has support for WSGI, your program
    344 can be deployed on every web server interface for which there are WSGI wrappers.
    345 So you do not need to care about whether the user uses mod_python or FastCGI --
    346 with WSGI it just works on any gateway interface.  The Python standard library
    347 contains its own WSGI server :mod:`wsgiref`, which is a small web server that
    348 can be used for testing.
    349 
    350 A really great WSGI feature are the middlewares.  Middlewares are layers around
    351 your program which can add various functionality to it.  There is a `number of
    352 middlewares <http://wsgi.org/wsgi/Middleware_and_Utilities>`_ already available.
    353 For example, instead of writing your own session management (to identify a user
    354 in subsequent requests, as HTTP does not maintain state, so it does now know
    355 that the requests belong to the same user) you can just take one middleware,
    356 plug it in and you can rely an already existing functionality.  The same thing
    357 is compression -- say you want to compress your HTML using gzip, to save your
    358 server's bandwidth.  So you only need to plug-in a middleware and you're done.
    359 Authentication is also a problem easily solved using a middleware.
    360 
    361 So, generally -- although WSGI may seem complex, the initial phase of learning
    362 can be very rewarding as WSGI does already have solutions to many problems that
    363 might arise while writing web sites.
     346WSGI has already been mentioned several times, so it has to be something
     347important.  In fact it really is, and now it is time to explain it.
     348
     349The *Web Server Gateway Interface*,  or WSGI for short, is defined in
     350:pep:`333` and is currently the best way to do Python web programming.  While
     351it is great for programmers writing frameworks, a normal web developer does not
     352need to get in direct contact with it.  When choosing a framework for web
     353development it is a good idea to choose one which supports WSGI.
     354
     355The big benefit of WSGI is the unification of the application programming
     356interface.  When your program is compatible with WSGI -- which at the outer
     357level means that the framework you are using has support for WSGI -- your
     358program can be deployed via any web server interface for which there are WSGI
     359wrappers.  You do not need to care about whether the application user uses
     360mod_python or FastCGI or mod_wsgi -- with WSGI your application will work on
     361any gateway interface.  The Python standard library contains its own WSGI
     362server, :mod:`wsgiref`, which is a small web server that can be used for
     363testing.
     364
     365A really great WSGI feature is middleware.  Middleware is a layer around your
     366program which can add various functionality to it.  There is quite a bit of
     367`middleware <http://www.wsgi.org/en/latest/libraries.html>`_ already
     368available.  For example, instead of writing your own session management (HTTP
     369is a stateless protocol, so to associate multiple HTTP requests with a single
     370user your application must create and manage such state via a session), you can
     371just download middleware which does that, plug it in, and get on with coding
     372the unique parts of your application.  The same thing with compression -- there
     373is existing middleware which handles compressing your HTML using gzip to save
     374on your server's bandwidth.  Authentication is another a problem easily solved
     375using existing middleware.
     376
     377Although WSGI may seem complex, the initial phase of learning can be very
     378rewarding because WSGI and the associated middleware already have solutions to
     379many problems that might arise while developing web sites.
    364380
    365381
     
    368384
    369385The code that is used to connect to various low level gateways like CGI or
    370 mod_python is called *WSGI server*.  One of these servers is ``flup`` which was
    371 already mentioned and supports FastCGI, SCGI as well as `AJP
     386mod_python is called a *WSGI server*.  One of these servers is ``flup``, which
     387supports FastCGI and SCGI, as well as `AJP
    372388<http://en.wikipedia.org/wiki/Apache_JServ_Protocol>`_.  Some of these servers
    373 are written in Python as ``flup`` is, but there also exist others which are
     389are written in Python, as ``flup`` is, but there also exist others which are
    374390written in C and can be used as drop-in replacements.
    375391
    376 There are quite a lot of servers already available, so a Python web application
    377 can be deployed nearly everywhere.  This is one big advantage that Python has
    378 compared with other web techniques.
    379 
    380 .. seealso::
    381 
    382    A good overview of all WSGI-related code can be found in the `WSGI wiki
    383    <http://wsgi.org/wsgi>`_, which contains an extensive list of `WSGI servers
    384    <http://wsgi.org/wsgi/Servers>`_, which can be used by *every* application
     392There are many servers already available, so a Python web application
     393can be deployed nearly anywhere.  This is one big advantage that Python has
     394compared with other web technologies.
     395
     396.. seealso::
     397
     398   A good overview of WSGI-related code can be found in the `WSGI homepage
     399   <http://www.wsgi.org/en/latest/index.html>`_, which contains an extensive list of `WSGI servers
     400   <http://www.wsgi.org/en/latest/servers.html>`_ which can be used by *any* application
    385401   supporting WSGI.
    386402
     
    394410--------------------
    395411
    396 What does WSGI give the web application developer?  Let's take a look on one
    397 long existing web application written in Python without using WSGI.
    398 
    399 One of the most widely used wiki software is `MoinMoin <http://moinmo.in/>`_.
    400 It was created in 2000, so it predates WSGI by about three years.  While it now
    401 includes support for WSGI, older versions needed separate code to run on CGI,
    402 mod_python, FastCGI and standalone.  Now, this all is possible by using WSGI and
    403 the already-written gateways.  For running with on FastCGI ``flup`` can be used,
    404 for running a standalone server :mod:`wsgiref` is the way to go.
    405 
    406 
    407 Model-view-controller
     412What does WSGI give the web application developer?  Let's take a look at
     413an application that's been around for a while, which was written in
     414Python without using WSGI.
     415
     416One of the most widely used wiki software packages is `MoinMoin
     417<http://moinmo.in/>`_.  It was created in 2000, so it predates WSGI by about
     418three years.  Older versions needed separate code to run on CGI, mod_python,
     419FastCGI and standalone.
     420
     421It now includes support for WSGI.  Using WSGI, it is possible to deploy
     422MoinMoin on any WSGI compliant server, with no additional glue code.
     423Unlike the pre-WSGI versions, this could include WSGI servers that the
     424authors of MoinMoin know nothing about.
     425
     426
     427Model-View-Controller
    408428=====================
    409429
    410 The term *MVC* is often heard in statements like "framework *foo* supports MVC".
    411 While MVC is not really something technical but rather organisational, many web
    412 frameworks use this model to help the developer to bring structure into his
    413 program.  Bigger web applications can have lots of code so it is a good idea to
    414 have structure in the program right from the beginnings.  That way, even users
    415 of other frameworks (or even languages, as MVC is nothing Python-specific) can
    416 understand the existing code easier, as they are already familiar with the
    417 structure.
     430The term *MVC* is often encountered in statements such as "framework *foo*
     431supports MVC".  MVC is more about the overall organization of code, rather than
     432any particular API.  Many web frameworks use this model to help the developer
     433bring structure to their program.  Bigger web applications can have lots of
     434code, so it is a good idea to have an effective structure right from the beginning.
     435That way, even users of other frameworks (or even other languages, since MVC is
     436not Python-specific) can easily understand the code, given that they are
     437already familiar with the MVC structure.
    418438
    419439MVC stands for three components:
    420440
    421 * The *model*.  This is the data that is meant to modify.  In Python frameworks
    422   this component is often represented by the classes used by the
    423   object-relational mapper.  So, all declarations go here.
     441* The *model*.  This is the data that will be displayed and modified.  In
     442  Python frameworks, this component is often represented by the classes used by
     443  an object-relational mapper.
     444
    424445* The *view*.  This component's job is to display the data of the model to the
    425   user.  Typically this component is represented by the templates.
     446  user.  Typically this component is implemented via templates.
     447
    426448* The *controller*.  This is the layer between the user and the model.  The
    427   controller reacts on user actions (like opening some specific URL) and tells
    428   the model to modify the data if necessary.
     449  controller reacts to user actions (like opening some specific URL), tells
     450  the model to modify the data if necessary, and tells the view code what to
     451  display,
    429452
    430453While one might think that MVC is a complex design pattern, in fact it is not.
     
    438461   (the model) from the user interaction logic (the controller) and the
    439462   templates (the view).  That's why it is important not to write unnecessary
    440    Python code in the templates -- it is against MVC and creates more chaos.
    441 
    442 .. seealso::
    443 
    444    The english Wikipedia has an article about the `Model-View-Controller pattern
    445    <http://en.wikipedia.org/wiki/Model-view-controller>`_, which includes a long
    446    list of web frameworks for different programming languages.
    447 
    448 
    449 Ingredients for web sites
    450 =========================
    451 
    452 Web sites are complex constructs, so tools were created to help the web site
    453 developer to make his work maintainable.  None of these tools are in any way
    454 Python specific, they also exist for other programming languages as well.  Of
    455 course, developers are not forced to use these tools and often there is no
    456 "best" tool, but it is worth informing yourself before choosing something
    457 because of the big number of helpers that the developer can use.
    458 
    459 
    460 .. seealso::
    461 
    462    People have written far more components that can be combined than these
    463    presented here.  The Python wiki has a page about these components, called
     463   Python code in the templates -- it works against the MVC model and creates
     464   chaos in the code base, making it harder to understand and modify.
     465
     466.. seealso::
     467
     468   The English Wikipedia has an article about the `Model-View-Controller pattern
     469   <http://en.wikipedia.org/wiki/Model-view-controller>`_.  It includes a long
     470   list of web frameworks for various programming languages.
     471
     472
     473Ingredients for Websites
     474========================
     475
     476Websites are complex constructs, so tools have been created to help web
     477developers make their code easier to write and more maintainable.  Tools like
     478these exist for all web frameworks in all languages.  Developers are not forced
     479to use these tools, and often there is no "best" tool.  It is worth learning
     480about the available tools because they can greatly simplify the process of
     481developing a web site.
     482
     483
     484.. seealso::
     485
     486   There are far more components than can be presented here.  The Python wiki
     487   has a page about these components, called
    464488   `Web Components <http://wiki.python.org/moin/WebComponents>`_.
    465489
     
    468492---------
    469493
    470 Mixing of HTML and Python code is possible with some libraries.  While
     494Mixing of HTML and Python code is made possible by a few libraries.  While
    471495convenient at first, it leads to horribly unmaintainable code.  That's why
    472496templates exist.  Templates are, in the simplest case, just HTML files with
    473 placeholders.  The HTML is sent to the user's browser after filling out the
     497placeholders.  The HTML is sent to the user's browser after filling in the
    474498placeholders.
    475499
    476 Python already includes such simple templates::
    477 
    478     # a simple template
    479     template = "<html><body><h1>Hello %s!</h1></body></html>"
    480     print template % "Reader"
    481 
    482 The Python standard library also includes some more advanced templates usable
    483 through :class:`string.Template`, but in HTML templates it is needed to use
    484 conditional and looping contructs like Python's *for* and *if*.  So, some
    485 *template engine* is needed.
    486 
    487 Now, Python has a lot of template engines which can be used with or without a
    488 `framework`_.  Some of these are using a plain-text programming language which
    489 is very easy to learn as it is quite limited while others use XML so the
    490 template output is always guaranteed to be valid XML.  Some `frameworks`_ ship
    491 their own template engine or recommend one particular.  If one is not yet sure,
    492 using these is a good idea.
    493 
    494 .. note::
    495 
    496    While Python has quite a lot of different template engines it usually does
    497    not make sense to use a homebrewed template system.  The time needed to
    498    evaluate all templating systems is not really worth it, better invest the
    499    time in looking through the most popular ones.  Some frameworks have their
    500    own template engine or have a recommentation for one.  It's wise to use
    501    these.
    502 
    503    Popular template engines include:
    504 
    505    * Mako
    506    * Genshi
    507    * Jinja
    508 
    509 .. seealso::
    510 
    511    Lots of different template engines divide the attention between themselves
    512    because it's easy to create them in Python.  The page `Templating
     500Python already includes two ways to build simple templates::
     501
     502    >>> template = "<html><body><h1>Hello %s!</h1></body></html>"
     503    >>> print template % "Reader"
     504    <html><body><h1>Hello Reader!</h1></body></html>
     505
     506    >>> from string import Template
     507    >>> template = Template("<html><body><h1>Hello ${name}</h1></body></html>")
     508    >>> print template.substitute(dict(name='Dinsdale'))
     509    <html><body><h1>Hello Dinsdale!</h1></body></html>
     510
     511To generate complex HTML based on non-trivial model data, conditional
     512and looping constructs like Python's *for* and *if* are generally needed.
     513*Template engines* support templates of this complexity.
     514
     515There are a lot of template engines available for Python which can be used with
     516or without a `framework`_.  Some of these define a plain-text programming
     517language which is easy to learn, partly because it is limited in scope.
     518Others use XML, and the template output is guaranteed to be always be valid
     519XML.  There are many other variations.
     520
     521Some `frameworks`_ ship their own template engine or recommend one in
     522particular.  In the absence of a reason to use a different template engine,
     523using the one provided by or recommended by the framework is a good idea.
     524
     525Popular template engines include:
     526
     527   * `Mako <http://www.makotemplates.org/>`_
     528   * `Genshi <http://genshi.edgewall.org/>`_
     529   * `Jinja <http://jinja.pocoo.org/2/>`_
     530
     531.. seealso::
     532
     533   There are many template engines competing for attention, because it is
     534   pretty easy to create them in Python.  The page `Templating
    513535   <http://wiki.python.org/moin/Templating>`_ in the wiki lists a big,
    514    ever-growing number of these.
     536   ever-growing number of these.  The three listed above are considered "second
     537   generation" template engines and are a good place to start.
    515538
    516539
     
    518541----------------
    519542
    520 *Data persistence*, while sounding very complicated is just about storing data.
    521 This data might be the text of blog entries, the postings of a bulletin board or
    522 the text of a wiki page.  As always, there are different ways to store
    523 informations on a web server.
    524 
    525 Often relational database engines like `MySQL <http://www.mysql.com/>`_ or
    526 `PostgreSQL <http://www.postgresql.org/>`_ are used due to their good
    527 performance handling very large databases consisting of up to millions of
    528 entries.  These are *queried* using a language called `SQL
    529 <http://en.wikipedia.org/wiki/SQL>`_.  Python programmers in general do not like
    530 SQL too much, they prefer to work with objects.  It is possible to save Python
    531 objects into a database using a technology called `ORM
    532 <http://en.wikipedia.org/wiki/Object-relational_mapping>`_.  ORM translates all
    533 object-oriented access into SQL code under the hood, the user does not need to
    534 think about it.  Most `frameworks`_ use ORMs and it works quite well.
    535 
    536 A second possibility is using files that are saved on the hard disk (sometimes
    537 called flatfiles).  This is very easy, but is not too fast.  There is even a
    538 small database engine called `SQLite <http://www.sqlite.org/>`_ which is bundled
    539 with Python in the :mod:`sqlite` module and uses only one file.  This database
    540 can be used to store objects via an ORM and has no other dependencies.  For
    541 smaller sites SQLite is just enough.  But it is not the only way in which data
    542 can be saved into the file systems.  Sometimes normal, plain text files are
    543 enough.
    544 
    545 The third and least used possibility are so-called object oriented databases.
    546 These databases store the *actual objects* instead of the relations that
    547 OR-mapping creates between rows in a database.  This has the advantage that
    548 nearly all objects can be saven in a straightforward way, unlike in relational
    549 databases where some objects are very hard to represent with ORMs.
    550 
    551 `Frameworks`_ often give the users hints on which method to choose, it is
    552 usually a good idea to stick to these unless there are some special requirements
    553 which require to use the one method and not the other.
     543*Data persistence*, while sounding very complicated, is just about storing data.
     544This data might be the text of blog entries, the postings on a bulletin board or
     545the text of a wiki page.  There are, of course, a number of different ways to store
     546information on a web server.
     547
     548Often, relational database engines like `MySQL <http://www.mysql.com/>`_ or
     549`PostgreSQL <http://www.postgresql.org/>`_ are used because of their good
     550performance when handling very large databases consisting of millions of
     551entries.  There is also a small database engine called `SQLite
     552<http://www.sqlite.org/>`_, which is bundled with Python in the :mod:`sqlite3`
     553module, and which uses only one file.  It has no other dependencies.  For
     554smaller sites SQLite is just enough.
     555
     556Relational databases are *queried* using a language called `SQL
     557<http://en.wikipedia.org/wiki/SQL>`_.  Python programmers in general do not
     558like SQL too much, as they prefer to work with objects.  It is possible to save
     559Python objects into a database using a technology called `ORM
     560<http://en.wikipedia.org/wiki/Object-relational_mapping>`_ (Object Relational
     561Mapping).  ORM translates all object-oriented access into SQL code under the
     562hood, so the developer does not need to think about it.  Most `frameworks`_ use
     563ORMs, and it works quite well.
     564
     565A second possibility is storing data in normal, plain text files (some
     566times called "flat files").  This is very easy for simple sites,
     567but can be difficult to get right if the web site is performing many
     568updates to the stored data.
     569
     570A third possibility are object oriented databases (also called "object
     571databases").  These databases store the object data in a form that closely
     572parallels the way the objects are structured in memory during program
     573execution.  (By contrast, ORMs store the object data as rows of data in tables
     574and relations between those rows.)  Storing the objects directly has the
     575advantage that nearly all objects can be saved in a straightforward way, unlike
     576in relational databases where some objects are very hard to represent.
     577
     578`Frameworks`_ often give hints on which data storage method to choose.  It is
     579usually a good idea to stick to the data store recommended by the framework
     580unless the application has special requirements better satisfied by an
     581alternate storage mechanism.
    554582
    555583.. seealso::
    556584
    557585   * `Persistence Tools <http://wiki.python.org/moin/PersistenceTools>`_ lists
    558      possibilities on how to save data in the file system, some of these modules
    559      are part of the standard library
     586     possibilities on how to save data in the file system.  Some of these
     587     modules are part of the standard library
     588
    560589   * `Database Programming <http://wiki.python.org/moin/DatabaseProgramming>`_
    561      helps on choosing a method on how to save the data
    562    * `SQLAlchemy <http://www.sqlalchemy.org/>`_, the most powerful OR-Mapper for
    563      Python and `Elixir <http://elixir.ematia.de/>`_ which makes it easier to
    564      use
     590     helps with choosing a method for saving data
     591
     592   * `SQLAlchemy <http://www.sqlalchemy.org/>`_, the most powerful OR-Mapper
     593     for Python, and `Elixir <http://elixir.ematia.de/>`_, which makes
     594     SQLAlchemy easier to use
     595
    565596   * `SQLObject <http://www.sqlobject.org/>`_, another popular OR-Mapper
     597
    566598   * `ZODB <https://launchpad.net/zodb>`_ and `Durus
    567599     <http://www.mems-exchange.org/software/durus/>`_, two object oriented
     
    574606==========
    575607
    576 As web sites can easily become quite large, there are so-called frameworks which
    577 were created to help the developer with making these sites.  Although the most
    578 well-known framework is Ruby on Rails, Python does also have its own frameworks
    579 which are partly inspired by Rails or which were existing a long time before
    580 Rails.
    581 
    582 Two possible approaches to web frameworks exist: the minimalistic approach and
    583 the all-inclusive approach (somtimes called *full-stack*). Frameworks which are
    584 all-inclusive give you everything you need to start working, like a template
    585 engine, some way to save and access data in databases and many features more.
    586 Most users are best off using these as they are widely used by lots of other
    587 users and well documented in form of books and tutorials.  Other web frameworks
    588 go the minimalistic approach trying to be as flexible as possible leaving the
    589 user the freedom to choose what's best for him.
    590 
    591 The majority of users is best off with all-inclusive framewors.  They bring
    592 everything along so a user can just jump in and start to code.  While they do
    593 have some limitations they can fullfill 80% of what one will ever want to
    594 perfectly.  They consist of various components which are designed to work
    595 together as good as possible.
    596 
    597 The multitude of web frameworks written in Python demonstrates that it is really
    598 easy to write one.  One of the most well-known web applications written in
    599 Python is `Zope <http://www.zope.org/>`_ which can be regarded as some kind of
    600 big framework.  But Zope was not the only framework, there were some others
    601 which are by now nearly forgotten.  These do not need to be mentioned anymore,
    602 because most people that used them moved on to newer ones.
     608The process of creating code to run web sites involves writing code to provide
     609various services.  The code to provide a particular service often works the
     610same way regardless of the complexity or purpose of the web site in question.
     611Abstracting these common solutions into reusable code produces what are called
     612"frameworks" for web development.  Perhaps the most well-known framework for
     613web development is Ruby on Rails, but Python has its own frameworks.  Some of
     614these were partly inspired by Rails, or borrowed ideas from Rails, but many
     615existed a long time before Rails.
     616
     617Originally Python web frameworks tended to incorporate all of the services
     618needed to develop web sites as a giant, integrated set of tools.  No two web
     619frameworks were interoperable:  a program developed for one could not be
     620deployed on a different one without considerable re-engineering work.  This led
     621to the development of "minimalist" web frameworks that provided just the tools
     622to communicate between the Python code and the http protocol, with all other
     623services to be added on top via separate components.  Some ad hoc standards
     624were developed that allowed for limited interoperability between frameworks,
     625such as a standard that allowed different template engines to be used
     626interchangeably.
     627
     628Since the advent of WSGI, the Python web framework world has been evolving
     629toward interoperability based on the WSGI standard.  Now many web frameworks,
     630whether "full stack" (providing all the tools one needs to deploy the most
     631complex web sites) or minimalist, or anything in between, are built from
     632collections of reusable components that can be used with more than one
     633framework.
     634
     635The majority of users will probably want to select a "full stack" framework
     636that has an active community.  These frameworks tend to be well documented,
     637and provide the easiest path to producing a fully functional web site in
     638minimal time.
    603639
    604640
     
    606642-----------------------
    607643
    608 There is an incredible number of frameworks, so there is no way to describe them
    609 all.  It is not even necessary, as most of these frameworks are nothing special
    610 and everything that can be done with these can also be done with one of the
    611 popular ones.
     644There are an incredible number of frameworks, so they cannot all be covered
     645here.  Instead we will briefly touch on some of the most popular.
    612646
    613647
     
    617651`Django <http://www.djangoproject.com/>`_ is a framework consisting of several
    618652tightly coupled elements which were written from scratch and work together very
    619 well.  It includes an ORM which is quite powerful while being simple to use and
    620 has a great online administration interface which makes it possible to edit the
    621 data in the database with a browser.  The template engine is text-based and is
    622 designed to be usable for page designers who cannot write Python.  It supports
    623 so-called template inheritance and filters (which work like Unix pipes).  Django
    624 has many handy features bundled, like creation of RSS feeds or generic views
    625 which make it possible to write web sites nearly without any Python code.
    626 
    627 It has a big, international community which has created many sites using Django.
    628 There are also quite a lot of add-on projects which extend Django's normal
     653well.  It includes an ORM which is quite powerful while being simple to use,
     654and has a great online administration interface which makes it possible to edit
     655the data in the database with a browser.  The template engine is text-based and
     656is designed to be usable for page designers who cannot write Python.  It
     657supports template inheritance and filters (which work like Unix pipes).  Django
     658has many handy features bundled, such as creation of RSS feeds or generic views,
     659which make it possible to create web sites almost without writing any Python code.
     660
     661It has a big, international community, the members of which have created many
     662web sites.  There are also a lot of add-on projects which extend Django's normal
    629663functionality.  This is partly due to Django's well written `online
    630664documentation <http://docs.djangoproject.com/>`_ and the `Django book
     
    634668.. note::
    635669
    636    Although Django is an MVC-style framework, it calls the components
     670   Although Django is an MVC-style framework, it names the elements
    637671   differently, which is described in the `Django FAQ
    638    <http://www.djangoproject.com/documentation/faq/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names>`_.
     672   <http://docs.djangoproject.com/en/dev/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names>`_.
    639673
    640674
     
    642676^^^^^^^^^^
    643677
    644 The other popular web framework in Python is `TurboGears
    645 <http://www.turbogears.org/>`_.  It takes the approach of using already existing
    646 components and combining them with glue code to create a seamless experience.
    647 TurboGears gives the user more flexibility on which components to choose, the
    648 ORM can be switched between some easy to use but limited and complex but very
    649 powerful.  Same goes for the template engine.  One strong point about TurboGears
    650 is that the components that it consists of can be used easily in other projects
    651 without depending on TurboGears, for example the underlying web server CherryPy.
     678Another popular web framework for Python is `TurboGears
     679<http://www.turbogears.org/>`_.  TurboGears takes the approach of using already
     680existing components and combining them with glue code to create a seamless
     681experience.  TurboGears gives the user flexibility in choosing components. For
     682example the ORM and template engine can be changed to use packages different
     683from those used by default.
    652684
    653685The documentation can be found in the `TurboGears wiki
     
    657689published, which is a good starting point.
    658690
    659 The plan for the next major version of TurboGears, version 2.0 is to switch to a
    660 more flexible base provided by another very flexible web framework called
    661 `Pylons <http://pylonshq.com/>`_.
     691The newest version of TurboGears, version 2.0, moves even further in direction
     692of WSGI support and a component-based architecture.  TurboGears 2 is based on
     693the WSGI stack of another popular component-based web framework, `Pylons
     694<http://pylonshq.com/>`_.
     695
     696
     697Zope
     698^^^^
     699
     700The Zope framework is one of the "old original" frameworks.  Its current
     701incarnation in Zope2 is a tightly integrated full-stack framework.  One of its
     702most interesting feature is its tight integration with a powerful object
     703database called the `ZODB <https://launchpad.net/zodb>`_ (Zope Object Database).
     704Because of its highly integrated nature, Zope wound up in a somewhat isolated
     705ecosystem:  code written for Zope wasn't very usable outside of Zope, and
     706vice-versa.  To solve this problem the Zope 3 effort was started.  Zope 3
     707re-engineers Zope as a set of more cleanly isolated components.  This effort
     708was started before the advent of the WSGI standard, but there is WSGI support
     709for Zope 3 from the `Repoze <http://repoze.org/>`_ project.  Zope components
     710have many years of production use behind them, and the Zope 3 project gives
     711access to these components to the wider Python community.  There is even a
     712separate framework based on the Zope components: `Grok
     713<http://grok.zope.org/>`_.
     714
     715Zope is also the infrastructure used by the `Plone <http://plone.org/>`_ content
     716management system, one of the most powerful and popular content management
     717systems available.
    662718
    663719
     
    665721^^^^^^^^^^^^^^^^^^^^^^^^
    666722
    667 These two are of course not the only frameworks that are available, there are
    668 also some less-popular frameworks worth mentioning.
    669 
    670 One of these is the already mentioned Zope, which has been around for quite a
    671 long time.  With Zope 2.x having been known as rather un-pythonic, the newer
    672 Zope 3.x tries to change that and therefore gets more acceptance from Python
    673 programmers.  These efforts already showed results, there is a project which
    674 connects Zope with WSGI called `Repoze <http://repoze.org/>`_ and another
    675 project called `Grok <http://grok.zope.org/>`_ which makes it possible for
    676 "normal" Python programmers use the very mature Zope components.
     723Of course these are not the only frameworks that are available.  There are
     724many other frameworks worth mentioning.
    677725
    678726Another framework that's already been mentioned is `Pylons`_.  Pylons is much
    679 like TurboGears with ab even stronger emphasis on flexibility, which is bought
     727like TurboGears, but with an even stronger emphasis on flexibility, which comes
    680728at the cost of being more difficult to use.  Nearly every component can be
    681729exchanged, which makes it necessary to use the documentation of every single
    682 component, because there are so many Pylons combinations possible that can
    683 satisfy every requirement.  Pylons builds upon `Paste
     730component, of which there are many.  Pylons builds upon `Paste
    684731<http://pythonpaste.org/>`_, an extensive set of tools which are handy for WSGI.
    685732
     
    693740
    694741   Most frameworks also have their own mailing lists and IRC channels, look out
    695    for these on the projects' websites.  There is also a general "Python in the
     742   for these on the projects' web sites.  There is also a general "Python in the
    696743   Web" IRC channel on freenode called `#python.web
    697744   <http://wiki.python.org/moin/PoundPythonWeb>`_.
Note: See TracChangeset for help on using the changeset viewer.