blob: 2440b3065467871aee0288b3f47a4f0a054a2d2c [file] [log] [blame]
Benjamin Petersonae5360b2008-09-08 23:05:23 +00001*******************************
2 HOWTO Use Python in the web
3*******************************
4
5:Author: Marek Kubica
6
7.. topic:: Abstract
8
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
11 developing web sites.
12
13
14Programming for the Web has become a hot topic since the raise of the "Web 2.0",
15which focuses on user-generated content on web sites. It has always been
16possible to use Python for creating web sites, but it was a rather tedious task.
17Therefore, many so-called "frameworks" and helper tools were created to help
18developers creating sites faster and these sites being more robust. This HOWTO
19describes some of the methods used to combine Python with a web server to create
20dynamic content. It is not meant as a general introduction as this topic is far
21too broad to be covered in one single document. However, a short overview of
22the 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
30 recent development.
31
32
33The low-level view
34==================
35
36.. .. image:: http.png
37
38When a user enters a web site, his browser makes a connection to the site's
39webserver (this is called the *request*). The server looks up the file in the
40file system and sends it back to the user's browser, which displays it (this is
41the *response*). This is roughly how the unterlying protocol, HTTP works.
42
43Now, dynamic web sites are not files in the file system, but rather programs
44which are run by the web server when a request comes in. They can do all sorts
45of useful things, like display the postings of a bulletin board, show your
46mails, configurate software or just display the current time. These programs
47can be written in about any programming language the server supports, so it is
48easy to use Python for creating dynamic web sites.
49
50As most of HTTP servers are written in C or C++, they cannot execute Python code
51in a simple way -- a bridge is needed between the server and the program. These
52bridges or rather interfaces define how programs interact with the server. In
53the past there have been numerous attempts to create the best possible
54interface, but there are only a few worth mentioning.
55
56Not every web server supports every interface. Many web servers do support only
57old, now-obsolete interfaces. But they can often be extended using some
58third-party modules to support new interfaces.
59
60
61Common Gateway Interface
62------------------------
63
64This interface is the oldest one, supported by nearly every web server out of
65the box. Programs using CGI to communicate with their web server need to be
66started by the server for every request. So, every request starts a new Python
67interpreter -- which takes some time to start up -- thus making the whole
68interface only usable for low load situations.
69
70The upside of CGI is that it is simple -- writing a program which uses CGI is a
71matter of about three lines of code. But this simplicity comes at a price: it
72does very few things to help the developer.
73
74Writing CGI programs, while still possible, is not recommended anymore. With
75WSGI (more on that later) it is possible to write programs that emulate CGI, so
76they can be run as CGI if no better option is available.
77
78.. seealso::
79
80 The Python standard library includes some modules that are helpful for
81 creating plain CGI programs:
82
83 * :mod:`cgi` -- Handling of user input in CGI scripts
84 * :mod:`cgitb` -- Displays nice tracebacks when errors happen in of CGI
85 applications, instead of presenting a "500 Internal Server Error" message
86
87 The Python wiki features a page on `CGI scripts
88 <http://wiki.python.org/moin/CgiScripts>`_ with some additional information
89 about CGI in Python.
90
Georg Brandl48310cd2009-01-03 21:18:54 +000091
Benjamin Petersonae5360b2008-09-08 23:05:23 +000092Simple script for testing CGI
93^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
94
95To test whether your web server works with CGI, you can use this short and
96simple CGI program::
97
98 #!/usr/bin/env python
99 # -*- coding: UTF-8 -*-
100
101 # enable debugging
Benjamin Petersonad3d5c22009-02-26 03:38:59 +0000102 import cgitb
103 cgitb.enable()
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000104
Georg Brandl6d204bf2008-12-05 18:04:41 +0000105 print("Content-Type: text/plain;charset=utf-8")
106 print()
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000107
Georg Brandl6d204bf2008-12-05 18:04:41 +0000108 print("Hello World!")
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000109
110You need to write this code into a file with a ``.py`` or ``.cgi`` extension,
111this depends on your web server configuration. Depending on your web server
112configuration, this file may also need to be in a ``cgi-bin`` folder, for
113security reasons.
114
115You might wonder what the ``cgitb`` line is about. This line makes it possible
116to display a nice traceback instead of just crashing and displaying an "Internal
117Server Error" in the user's browser. This is useful for debugging, but it might
118risk exposing some confident data to the user. Don't use it when the script is
119ready for production use. Still, you should *always* catch exceptions, and
120display proper error pages -- end-users don't like to see nondescript "Internal
121Server Errors" in their browsers.
122
123
124Setting up CGI on your own server
125^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
126
127If you don't have your own web server, this does not apply to you. You can
128check whether if works as-is and if not you need to talk to the administrator of
129your web server anyway. If it is a big hoster, you can try filing a ticket
130asking for Python support.
131
132If you're your own administrator or want to install it for testing purposes on
133your own computers, you have to configure it by yourself. There is no one and
134single way on how to configure CGI, as there are many web servers with different
135configuration options. The currently most widely used free web server is
136`Apache HTTPd <http://httpd.apache.org/>`_, Apache for short -- this is the one
137that most people use, it can be easily installed on nearly every system using
138the systems' package management. But `lighttpd <http://www.lighttpd.net>`_ has
139been gaining attention since some time and is said to have a better performance.
140On many systems this server can also be installed using the package management,
141so manually compiling the web server is never needed.
142
143* On Apache you can take a look into the `Dynamic Content with CGI
144 <http://httpd.apache.org/docs/2.2/howto/cgi.html>`_ tutorial, where everything
145 is described. Most of the time it is enough just to set ``+ExecCGI``. The
146 tutorial also describes the most common gotchas that might arise.
147* On lighttpd you need to use the `CGI module
148 <http://trac.lighttpd.net/trac/wiki/Docs%3AModCGI>`_ which can be configured
149 in a straightforward way. It boils down to setting ``cgi.assign`` properly.
150
151
152Common problems with CGI scripts
153^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
154
155Trying to use CGI sometimes leads to small annoyances that one might experience
156while trying to get these scripts to run. Sometimes it happens that a seemingly
157correct script does not work as expected, which is caused by some small hidden
158reason that's difficult to spot.
159
160Some 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
164 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``.
188* 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.
195
196
197.. _mod-python:
198
199mod_python
200----------
201
202People coming from PHP often find it hard to grasp how to use Python in the web.
203Their first thought is mostly `mod_python <http://www.modpython.org/>`_ because
204they think that this is the equivalent to ``mod_php``. Actually it is not
205really. It does embed the interpreter into the Apache process, thus speeding up
206requests by not having to start a Python interpreter every request. On the
207other hand, it is by far not "Python intermixed with HTML" as PHP often does.
208The Python equivalent of that is a template engine. mod_python itself is much
209more powerful and gives more access to Apache internals. It can emulate CGI, it
210can work an a "Python Server Pages" mode similar to JSP which is "HTML
211intermangled with Python" and it has a "Publisher" which destignates one file to
212accept all requests and decide on what to do then.
213
214But mod_python has some problems. Unlike the PHP interpreter the Python
215interpreter uses caching when executing files, so when changing a file the whole
216web server needs to be re-started to update. Another problem ist the basic
217concept -- Apache starts some child processes to handle the requests and
218unfortunately every child process needs to load the whole Python interpreter
219even if it does not use it. This makes the whole web server slower. Another
220problem 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
223the Apache web server, so programs written for mod_python cannot easily run on
224other web servers.
225
226These are the reasons why mod_python should be avoided when writing new
227programs. In some circumstances it might be still a good idea to use mod_python
228for deployment, but WSGI makes it possible to run WSGI programs under mod_python
229as well.
230
231
232FastCGI and SCGI
233----------------
234
235FastCGI and SCGI try to solve the performance problem of CGI in another way.
236Instead of embedding the interpreter into the web server, they create
237long-running processes which run in the background. There still is some module
238in the web server which makes it possible for the web server to "speak" with the
239background process. As the background process is independent from the server,
240it can be written in any language of course also in Python. The language just
241needs to have a library which handles the communication with the web server.
242
243The difference between FastCGI and SCGI is very small, as SCGI is essentially
244just a "simpler FastCGI". But as the web server support for SCGI is limited
245most people use FastCGI instead, which works the same way. Almost everything
246that applies to SCGI also applies to FastCGI as well, so we'll only write about
247the latter.
248
249These days, FastCGI is never used directly. Just like ``mod_python`` it is only
250used for the deployment of WSGI applications.
251
252.. seealso::
253
254 * `FastCGI, SCGI, and Apache: Background and Future
255 <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
257 of mod_python.
258
259
260Setting up FastCGI
261^^^^^^^^^^^^^^^^^^
262
263Depending 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
269 to be loaded by Apache.
270* 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
274 <http://wiki.codemongers.com/NginxSimplePythonFCGI>`_.
275
276Once you have installed and configured the module, you can test it with the
277following WSGI-application::
278
279 #!/usr/bin/env python
280 # -*- coding: UTF-8 -*-
281
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000282 import sys, os
Georg Brandl6d204bf2008-12-05 18:04:41 +0000283 from cgi import escape
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000284 from flup.server.fcgi import WSGIServer
285
286 def app(environ, start_response):
287 start_response('200 OK', [('Content-Type', 'text/html')])
288
289 yield '<h1>FastCGI Environment</h1>'
290 yield '<table>'
291 for k, v in sorted(environ.items()):
Georg Brandl6d204bf2008-12-05 18:04:41 +0000292 yield '<tr><th>{0}</th><td>{1}</td></tr>'.format(
293 escape(k), escape(v))
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000294 yield '</table>'
295
296 WSGIServer(app).run()
297
298This is a simple WSGI application, but you need to install `flup
299<http://pypi.python.org/pypi/flup/1.0>`_ first, as flup handles the low level
300FastCGI access.
301
302.. seealso::
303
304 There is some documentation on `setting up Django with FastCGI
305 <http://www.djangoproject.com/documentation/fastcgi/>`_, most of which can be
306 reused for other WSGI-compliant frameworks and libraries. Only the
307 ``manage.py`` part has to be changed, the example used here can be used
308 instead. Django does more or less the exact same thing.
309
310
311mod_wsgi
312--------
313
314`mod_wsgi <http://www.modwsgi.org/>`_ is an attempt to get rid of the low level
315gateways. As FastCGI, SCGI, mod_python are mostly used to deploy WSGI
316applications anyway, mod_wsgi was started to directly embed WSGI aplications
317into the Apache web server. The benefit from this approach is that WSGI
318applications can be deployed much easier as is is specially designed to host
319WSGI applications -- unlike the other low level methods which have glue code to
320host WSGI applications (like flup which was mentioned before). The downside is
321that mod_wsgi is limited to the Apache web server, other servers would need
322their own implementations of mod_wsgi.
323
324It supports two modes: the embedded mode in which it integrates with the Apache
325process and the daemon mode which is more FastCGI-like. Contrary to FastCGI,
326mod_wsgi handles the worker-processes by itself which makes administration
327easier.
328
329
330.. _WSGI:
331
332Step back: WSGI
333===============
334
335WSGI was already mentioned several times so it has to be something important.
336In fact it really is, so now it's time to explain.
337
338The *Web Server Gateway Interface*, :pep:`333` or WSGI for short is currently
339the best possible way to Python web programming. While it is great for
340programmers writing frameworks, the normal person does not need to get in direct
341contact with it. But when choosing a framework for web development it is a good
342idea to take one which supports WSGI.
343
344The big profit from WSGI is the unification. When your program is compatible
345with WSGI -- that means that your framework has support for WSGI, your program
346can be deployed on every web server interface for which there are WSGI wrappers.
347So you do not need to care about whether the user uses mod_python or FastCGI --
348with WSGI it just works on any gateway interface. The Python standard library
349contains its own WSGI server :mod:`wsgiref`, which is a small web server that
350can be used for testing.
351
352A really great WSGI feature are the middlewares. Middlewares are layers around
353your program which can add various functionality to it. There is a `number of
354middlewares <http://wsgi.org/wsgi/Middleware_and_Utilities>`_ already available.
355For example, instead of writing your own session management (to identify a user
356in subsequent requests, as HTTP does not maintain state, so it does now know
357that the requests belong to the same user) you can just take one middleware,
358plug it in and you can rely an already existing functionality. The same thing
359is compression -- say you want to compress your HTML using gzip, to save your
360server's bandwidth. So you only need to plug-in a middleware and you're done.
361Authentication is also a problem easily solved using a middleware.
362
363So, generally -- although WSGI may seem complex, the initial phase of learning
364can be very rewarding as WSGI does already have solutions to many problems that
365might arise while writing web sites.
366
367
368WSGI Servers
369------------
370
371The code that is used to connect to various low level gateways like CGI or
372mod_python is called *WSGI server*. One of these servers is ``flup`` which was
373already mentioned and supports FastCGI, SCGI as well as `AJP
374<http://en.wikipedia.org/wiki/Apache_JServ_Protocol>`_. Some of these servers
375are written in Python as ``flup`` is, but there also exist others which are
376written in C and can be used as drop-in replacements.
377
378There are quite a lot of servers already available, so a Python web application
379can be deployed nearly everywhere. This is one big advantage that Python has
380compared with other web techniques.
381
382.. seealso::
383
384 A good overview of all WSGI-related code can be found in the `WSGI wiki
385 <http://wsgi.org/wsgi>`_, which contains an extensive list of `WSGI servers
386 <http://wsgi.org/wsgi/Servers>`_, which can be used by *every* application
387 supporting WSGI.
388
389 You might be interested in some WSGI-supporting modules already contained in
390 the standard library, namely:
Georg Brandl48310cd2009-01-03 21:18:54 +0000391
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000392 * :mod:`wsgiref` -- some tiny utilities and servers for WSGI
393
394
395Case study: MoinMoin
396--------------------
397
398What does WSGI give the web application developer? Let's take a look on one
399long existing web application written in Python without using WSGI.
400
401One of the most widely used wiki software is `MoinMoin <http://moinmo.in/>`_.
402It was created in 2000, so it predates WSGI by about three years. While it now
403includes support for WSGI, older versions needed separate code to run on CGI,
404mod_python, FastCGI and standalone. Now, this all is possible by using WSGI and
405the already-written gateways. For running with on FastCGI ``flup`` can be used,
406for running a standalone server :mod:`wsgiref` is the way to go.
407
408
409Model-view-controller
410=====================
411
412The term *MVC* is often heard in statements like "framework *foo* supports MVC".
413While MVC is not really something technical but rather organisational, many web
414frameworks use this model to help the developer to bring structure into his
415program. Bigger web applications can have lots of code so it is a good idea to
416have structure in the program right from the beginnings. That way, even users
417of other frameworks (or even languages, as MVC is nothing Python-specific) can
418understand the existing code easier, as they are already familiar with the
419structure.
420
421MVC stands for three components:
422
423* The *model*. This is the data that is meant to modify. In Python frameworks
424 this component is often represented by the classes used by the
425 object-relational mapper. So, all declarations go here.
426* The *view*. This component's job is to display the data of the model to the
427 user. Typically this component is represented by the templates.
428* The *controller*. This is the layer between the user and the model. The
429 controller reacts on user actions (like opening some specific URL) and tells
Mark Dickinson934896d2009-02-21 20:59:32 +0000430 the model to modify the data if necessary.
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000431
432While one might think that MVC is a complex design pattern, in fact it is not.
433It is used in Python because it has turned out to be useful for creating clean,
434maintainable web sites.
435
436.. note::
437
438 While not all Python frameworks explicitly support MVC, it is often trivial
Mark Dickinson934896d2009-02-21 20:59:32 +0000439 to create a web site which uses the MVC pattern by separating the data logic
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000440 (the model) from the user interaction logic (the controller) and the
Mark Dickinson934896d2009-02-21 20:59:32 +0000441 templates (the view). That's why it is important not to write unnecessary
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000442 Python code in the templates -- it is against MVC and creates more chaos.
443
444.. seealso::
445
446 The english Wikipedia has an article about the `Model-View-Controller pattern
447 <http://en.wikipedia.org/wiki/Model-view-controller>`_, which includes a long
448 list of web frameworks for different programming languages.
449
450
451Ingredients for web sites
452=========================
453
454Web sites are complex constructs, so tools were created to help the web site
455developer to make his work maintainable. None of these tools are in any way
456Python specific, they also exist for other programming languages as well. Of
457course, developers are not forced to use these tools and often there is no
458"best" tool, but it is worth informing yourself before choosing something
459because of the big number of helpers that the developer can use.
460
461
462.. seealso::
463
464 People have written far more components that can be combined than these
465 presented here. The Python wiki has a page about these components, called
466 `Web Components <http://wiki.python.org/moin/WebComponents>`_.
467
468
469Templates
470---------
471
472Mixing of HTML and Python code is possible with some libraries. While
473convenient at first, it leads to horribly unmaintainable code. That's why
474templates exist. Templates are, in the simplest case, just HTML files with
475placeholders. The HTML is sent to the user's browser after filling out the
476placeholders.
477
478Python already includes such simple templates::
479
480 # a simple template
Georg Brandl6d204bf2008-12-05 18:04:41 +0000481 template = "<html><body><h1>Hello {who}!</h1></body></html>"
482 print(template.format(who="Reader"))
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000483
484The Python standard library also includes some more advanced templates usable
485through :class:`string.Template`, but in HTML templates it is needed to use
486conditional and looping contructs like Python's *for* and *if*. So, some
487*template engine* is needed.
488
489Now, Python has a lot of template engines which can be used with or without a
490`framework`_. Some of these are using a plain-text programming language which
491is very easy to learn as it is quite limited while others use XML so the
492template output is always guaranteed to be valid XML. Some `frameworks`_ ship
493their own template engine or recommend one particular. If one is not yet sure,
494using these is a good idea.
495
496.. note::
497
498 While Python has quite a lot of different template engines it usually does
499 not make sense to use a homebrewed template system. The time needed to
500 evaluate all templating systems is not really worth it, better invest the
501 time in looking through the most popular ones. Some frameworks have their
502 own template engine or have a recommentation for one. It's wise to use
503 these.
Georg Brandl48310cd2009-01-03 21:18:54 +0000504
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000505 Popular template engines include:
506
507 * Mako
508 * Genshi
509 * Jinja
510
511.. seealso::
512
513 Lots of different template engines divide the attention between themselves
514 because it's easy to create them in Python. The page `Templating
515 <http://wiki.python.org/moin/Templating>`_ in the wiki lists a big,
516 ever-growing number of these.
517
518
519Data persistence
520----------------
521
522*Data persistence*, while sounding very complicated is just about storing data.
523This data might be the text of blog entries, the postings of a bulletin board or
524the text of a wiki page. As always, there are different ways to store
525informations on a web server.
526
527Often relational database engines like `MySQL <http://www.mysql.com/>`_ or
528`PostgreSQL <http://http://www.postgresql.org/>`_ are used due to their good
529performance handling very large databases consisting of up to millions of
530entries. These are *queried* using a language called `SQL
531<http://en.wikipedia.org/wiki/SQL>`_. Python programmers in general do not like
532SQL too much, they prefer to work with objects. It is possible to save Python
533objects into a database using a technology called `ORM
534<http://en.wikipedia.org/wiki/Object-relational_mapping>`_. ORM translates all
535object-oriented access into SQL code under the hood, the user does not need to
536think about it. Most `frameworks`_ use ORMs and it works quite well.
537
538A second possibility is using files that are saved on the hard disk (sometimes
539called flatfiles). This is very easy, but is not too fast. There is even a
540small database engine called `SQLite <http://www.sqlite.org/>`_ which is bundled
541with Python in the :mod:`sqlite` module and uses only one file. This database
542can be used to store objects via an ORM and has no other dependencies. For
543smaller sites SQLite is just enough. But it is not the only way in which data
544can be saved into the file systems. Sometimes normal, plain text files are
545enough.
546
547The third and least used possibility are so-called object oriented databases.
548These databases store the *actual objects* instead of the relations that
549OR-mapping creates between rows in a database. This has the advantage that
550nearly all objects can be saven in a straightforward way, unlike in relational
551databases where some objects are very hard to represent with ORMs.
552
553`Frameworks`_ often give the users hints on which method to choose, it is
554usually a good idea to stick to these unless there are some special requirements
555which require to use the one method and not the other.
556
557.. seealso::
558
559 * `Persistence Tools <http://wiki.python.org/moin/PersistenceTools>`_ lists
560 possibilities on how to save data in the file system, some of these modules
561 are part of the standard library
562 * `Database Programming <http://wiki.python.org/moin/DatabaseProgramming>`_
563 helps on choosing a method on how to save the data
564 * `SQLAlchemy <http://www.sqlalchemy.org/>`_, the most powerful OR-Mapper for
565 Python and `Elixir <http://elixir.ematia.de/>`_ which makes it easier to
566 use
567 * `SQLObject <http://www.sqlobject.org/>`_, another popular OR-Mapper
568 * `ZODB <https://launchpad.net/zodb>`_ and `Durus
569 <http://www.mems-exchange.org/software/durus/>`_, two object oriented
570 databases
571
572
573.. _framework:
574
575Frameworks
576==========
577
578As web sites can easily become quite large, there are so-called frameworks which
579were created to help the developer with making these sites. Although the most
580well-known framework is Ruby on Rails, Python does also have its own frameworks
581which are partly inspired by Rails or which were existing a long time before
582Rails.
583
584Two possible approaches to web frameworks exist: the minimalistic approach and
585the all-inclusive approach (somtimes called *full-stack*). Frameworks which are
586all-inclusive give you everything you need to start working, like a template
587engine, some way to save and access data in databases and many features more.
588Most users are best off using these as they are widely used by lots of other
589users and well documented in form of books and tutorials. Other web frameworks
590go the minimalistic approach trying to be as flexible as possible leaving the
591user the freedom to choose what's best for him.
592
593The majority of users is best off with all-inclusive framewors. They bring
594everything along so a user can just jump in and start to code. While they do
595have some limitations they can fullfill 80% of what one will ever want to
596perfectly. They consist of various components which are designed to work
597together as good as possible.
598
599The multitude of web frameworks written in Python demonstrates that it is really
600easy to write one. One of the most well-known web applications written in
601Python is `Zope <http://www.zope.org/>`_ which can be regarded as some kind of
602big framework. But Zope was not the only framework, there were some others
603which are by now nearly forgotten. These do not need to be mentioned anymore,
604because most people that used them moved on to newer ones.
605
606
607Some notable frameworks
608-----------------------
609
610There is an incredible number of frameworks, so there is no way to describe them
Mark Dickinson934896d2009-02-21 20:59:32 +0000611all. It is not even necessary, as most of these frameworks are nothing special
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000612and everything that can be done with these can also be done with one of the
613popular ones.
614
615
616Django
617^^^^^^
618
619`Django <http://www.djangoproject.com/>`_ is a framework consisting of several
620tightly coupled elements which were written from scratch and work together very
621well. It includes an ORM which is quite powerful while being simple to use and
622has a great online administration interface which makes it possible to edit the
623data in the database with a browser. The template engine is text-based and is
624designed to be usable for page designers who cannot write Python. It supports
625so-called template inheritance and filters (which work like Unix pipes). Django
626has many handy features bundled, like creation of RSS feeds or generic views
627which make it possible to write web sites nearly without any Python code.
628
629It has a big, international community which has created many sites using Django.
630There are also quite a lot of add-on projects which extend Django's normal
631functionality. This is partly due to Django's well written `online
632documentation <http://doc.djangoproject.com/>`_ and the `Django book
633<http://www.djangobook.com/>`_.
634
635
636.. note::
637
638 Although Django is an MVC-style framework, it calls the components
639 differently, which is described in the `Django FAQ
640 <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>`_.
641
642
643TurboGears
644^^^^^^^^^^
645
646The other popular web framework in Python is `TurboGears
647<http://www.turbogears.org/>`_. It takes the approach of using already existing
648components and combining them with glue code to create a seamless experience.
649TurboGears gives the user more flexibility on which components to choose, the
650ORM can be switched between some easy to use but limited and complex but very
651powerful. Same goes for the template engine. One strong point about TurboGears
652is that the components that it consists of can be used easily in other projects
653without depending on TurboGears, for example the underlying web server CherryPy.
654
655The documentation can be found in the `TurboGears wiki
656<http://docs.turbogears.org/>`_, where links to screencasts can be found.
657TurboGears has also an active user community which can respond to most related
658questions. There is also a `TurboGears book <http://turbogearsbook.com/>`_
659published, which is a good starting point.
660
661The plan for the next major version of TurboGears, version 2.0 is to switch to a
662more flexible base provided by another very flexible web framework called
663`Pylons <http://pylonshq.com/>`_.
664
665
666Other notable frameworks
667^^^^^^^^^^^^^^^^^^^^^^^^
668
669These two are of course not the only frameworks that are available, there are
670also some less-popular frameworks worth mentioning.
671
672One of these is the already mentioned Zope, which has been around for quite a
673long time. With Zope 2.x having been known as rather un-pythonic, the newer
674Zope 3.x tries to change that and therefore gets more acceptance from Python
675programmers. These efforts already showed results, there is a project which
676connects Zope with WSGI called `Repoze <http://repoze.org/>`_ and another
677project called `Grok <http://grok.zope.org/>`_ which makes it possible for
678"normal" Python programmers use the very mature Zope components.
679
680Another framework that's already been mentioned is `Pylons`_. Pylons is much
681like TurboGears with ab even stronger emphasis on flexibility, which is bought
682at the cost of being more difficult to use. Nearly every component can be
Mark Dickinson934896d2009-02-21 20:59:32 +0000683exchanged, which makes it necessary to use the documentation of every single
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000684component, because there are so many Pylons combinations possible that can
685satisfy every requirement. Pylons builds upon `Paste
686<http://pythonpaste.org/>`_, an extensive set of tools which are handy for WSGI.
687
688And that's still not everything. The most up-to-date information can always be
689found in the Python wiki.
690
691.. seealso::
Georg Brandl48310cd2009-01-03 21:18:54 +0000692
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000693 The Python wiki contains an extensive list of `web frameworks
694 <http://wiki.python.org/moin/WebFrameworks>`_.
695
696 Most frameworks also have their own mailing lists and IRC channels, look out
697 for these on the projects' websites. There is also a general "Python in the
698 Web" IRC channel on freenode called `#python.web
699 <http://wiki.python.org/moin/PoundPythonWeb>`_.