# Introduction
[web2py](http://web2py.com) ([link](http://www.web2py.com)) is a free, open-source web framework for agile development of secure database-driven web applications; it is written in [Python](http://www.python.org) and programmable in Python. [web2py](http://web2py.com) is a full-stack framework, meaning that it contains all the components you need to build fully functional web applications.
[web2py](http://web2py.com) is designed to guide a web developer to follow good software engineering practices, such as using the Model View Controller (MVC) pattern. [web2py](http://web2py.com) separates the data representation (the model) from the data presentation (the view) and also from the application logic and workflow (the controller). [web2py](http://web2py.com) provides libraries to help the developer design, implement, and test each of these three parts separately, and makes them work together.
[web2py](http://web2py.com) is built for security. This means that it automatically addresses many of the issues that can lead to security vulnerabilities, by following well established practices. For example, it validates all input (to prevent injections), escapes all output (to prevent cross-site scripting), renames uploaded files (to prevent directory traversal attacks), and stores all session information server side. [web2py](http://web2py.com) leaves little choice to application developers in matters related to security.
[web2py](http://web2py.com) includes a Database Abstraction Layer (DAL) that writes [SQL](http://en.wikipedia.org/wiki/SQL) dynamically so that the developer does not have to. The DAL knows how to generate SQL transparently for [SQLite](http://www.sqlite.org/), [MySQL](http://www.mysql.com/), [PostgreSQL](http://www.postgresql.org/), [MSSQL](http://www.microsoft.com/sqlserver), [FireBird](http://www.firebirdsql.org/), [Oracle](http://www.oracle.com/database/index.html), IBM [DB2](http://www-01.ibm.com/software/data/db2/) and [Informix](http://www-01.ibm.com/software/data/informix/). The DAL can also generate function calls for Google BigTable when running on the Google App Engine (GAE) ([link](http://code.google.com/appengine/)). Once one or more database tables are defined, [web2py](http://web2py.com) also generates a fully functional web-based database administration interface to access the database and the tables.
[web2py](http://web2py.com) differs from other web frameworks in that it is the only framework to fully embrace the Web 2.0 paradigm, where the web is the computer. In fact, [web2py](http://web2py.com) does not require installation or configuration; it runs on any architecture that can run Python (Windows, Windows CE, Mac OS X, iPhone, and Unix/Linux), and the development, deployment, and maintenance phases for the applications can be done via a local or remote web interface. [web2py](http://web2py.com) runs with CPython (the C implementation) and/or Jython (the Java implementation), versions 2.4, 2.5 and 2.6 although "officially" only support 2.5 else we cannot guarantee backward compatibility for applications.
[web2py](http://web2py.com) provides a ticketing system. If an error occurs, a ticket is issued to the user, and the error is logged for the administrator.
[web2py](http://web2py.com) is open source and released under the GPL2.0 license, but [web2py](http://web2py.com) developed applications are not subject to any license constraint. As long as applications do not explicitly contain [web2py](http://web2py.com) source code, they are not considered "derivative works". [web2py](http://web2py.com) also allows the developer to bytecode-compile applications and distribute them as closed source, although they will require [web2py](http://web2py.com) to run. The [web2py](http://web2py.com) license includes an exception that allows web developers to ship their products with original pre-compiled [web2py](http://web2py.com) binaries, without the accompanying source code.
Another feature of [web2py](http://web2py.com), is that we, its developers, commit to maintain backward compatibility in future versions. We have done so since the first release of [web2py](http://web2py.com) in October, 2007. New features have been added and bugs have been fixed, but if a program worked with [web2py](http://web2py.com) 1.0, that program will still work today.
Here are some examples of [web2py](http://web2py.com) statements that illustrate its power and simplicity. The following code:
db.define_table('person',
Field('name', 'string'),
Field('image', 'upload'))
creates a database table called "person" with two fields: "name", a string; and "image", something that needs to be uploaded (the actual image). If the table already exists but does not match this definition, it is altered appropriately.
Given the table defined above, the following code:
form = SQLFORM(db.person)
creates an insert form for this table that allows users to upload images.
The following statement:
if form.accepts(request.vars, session):
pass
validates a submitted form, renames the uploaded image in a secure way, stores the image in a file, inserts the corresponding record in the database, prevents double submission, and eventually modifies the form itself by adding error messages if the data submitted by the user does not pass validation.
## Principles
Python programming typically follows these basic principles:
* Don't repeat yourself (DRY).
* There should be only one way of doing things.
* Explicit is better than implicit.
[web2py](http://web2py.com) fully embraces the first two principles by forcing the developer to use sound software engineering practices that discourage repetition of code. [web2py](http://web2py.com) guides the developer through almost all the tasks common in web application development (creating and processing forms, managing sessions, cookies, errors, etc.).
[web2py](http://web2py.com) differs from other frameworks with regard to the third principle, which sometimes conflicts with the other two. In particular, [web2py](http://web2py.com) automatically imports its own modules and instantiates its global objects (request, response, session, cache, T) and this is done "under the hood". To some this may appear as magic, but it should not. [web2py](http://web2py.com) is trying to avoid the annoying characteristic of other frameworks that force the developer to import the same modules at the top of every model and controller.
[web2py](http://web2py.com), by importing its own modules, saves time and prevents mistakes, thus following the spirit of "don't repeat yourself" and "there should be only one way of doing things".
If the developer wishes to use other Python modules or third-party modules, those modules must be imported explicitly, as in any other Python program.
## Web Frameworks
At its most fundamental level, a web application consists of a set of programs (or functions) that are executed when a URL is visited. The output of the program is returned to the visitor and rendered by the browser.
The two classic approaches for developing web applications are:
* Generating [HTML](http://en.wikipedia.org/wiki/HTML) ([link](http://www.w3.org/TR/REC-html40/)) programmatically and embedding HTML as strings into computer code.
* Embedding pieces of code into HTML pages.
The first model is the one followed, for example, by early CGI scripts. The second model is followed, for example, by [PHP](http://www.php.net/) (where the code is in PHP, a C-like language), ASP (where the code is in Visual Basic), and JSP (where the code is in Java).
Here we present an example of a PHP program that, when executed, retrieves data from a database and returns an HTML page showing the selected records:
Records
mysql_connect(localhost,username,password);
@mysql_select_db(database) or die( "Unable to select database");
$query="SELECT * FROM contacts";
$result=mysql_query($query);
mysql_close();
$i=0;
while ($i < mysql_numrows($result)) {
$name=mysql_result($result,$i,"name");
$phone=mysql_result($result,$i,"phone");
echo "$name
Phone:$phone
";
$i++;
}
?>
The problem with this approach is that code is embedded into HTML, but this very same code also needs to generate additional HTML and to generate SQL statements to query the database, entangling multiple layers of the application and making it difficult to read and maintain. The situation is even worse for Ajax applications, and the complexity grows with the number of pages (files) that make up the application.
The functionality of the above example can be expressed in [web2py](http://web2py.com) with two lines of Python code:
def index():
return HTML(BODY(H1('Records'), db().select(db.contacts.ALL)))
In this simple example, the HTML page structure is represented programmatically by the `HTML`, `BODY`, and `H1` objects; the database `db` (There is nothing special about the name `db`; it is just a variable holding your database connection.) is queried by the `select` command; finally, everything is serialized into HTML.
This is just one example of the power of [web2py](http://web2py.com) and its built-in libraries. [web2py](http://web2py.com) does even more for the developer by automatically handling cookies, sessions, creation of database tables, database modifications, form validation, SQL injection prevention, cross-site scripting (XSS) prevention, and many other indispensable web application tasks.
Web frameworks are typically categorized as one of two types: A "glued" framework is built by assembling (gluing together) several third-party components. A "full-stack" framework is built by creating components designed specifically to work together and be tightly integrated.
[web2py](http://web2py.com) is a full-stack framework. Almost all of its components are built from scratch and designed to work together, but they function just as well outside of the complete [web2py](http://web2py.com) framework. For example, the Database Abstraction Layer (DAL) or the template language can be used independently of the [web2py](http://web2py.com) framework by importing `gluon.sql` or `gluon.template` into your own Python applications. `gluon` is the name of the [web2py](http://web2py.com) folder that contains system libraries. Some [web2py](http://web2py.com) libraries, such as building and processing forms from database tables, have dependencies on other portions of [web2py](http://web2py.com). [web2py](http://web2py.com) can also work with third-party Python libraries, including other template languages and DALs, but they will not be as tightly integrated as the original components.
## Model-View-Controller
[web2py](http://web2py.com) forces the developer to separate data representation (the model), data presentation (the view) and the application workflow (the controller). Let's consider again the previous example and see how to build a [web2py](http://web2py.com) application around it.

The typical workflow of a request in [web2py](http://web2py.com) is described in the following diagram:

In the diagram:
* The Server can be the [web2py](http://web2py.com) built-in web server or a third-party server, such as Apache. The Server handles multi-threading.
* Main is the main [web2py](http://web2py.com) WSGI application. It performs all common tasks and wraps user applications. It deals with cookies, sessions, transactions, url mapping and reverse mapping, dispatching (deciding which function to call based on the URL). It can serve and stream static files if the web server is not doing it already.
* The Models, Views and Controller components make up the user application. There can be multiple applications hosted in the same [web2py](http://web2py.com) instance.
* The dashed arrows represent communication with the database engine (or engines). The database queries can be written in raw SQL (discouraged) or by using the [web2py](http://web2py.com) Database Abstraction Layer (recommended), so that that [web2py](http://web2py.com) application code is not dependent on the specific database engine.
* The dispatcher maps the requested URL into a function call in the controller. The output of the function can be a string or a dictionary of symbols (a hash table). The data in the dictionary is rendered by a view. If the visitor requests an HTML page (the default), the dictionary is rendered into an HTML page. If the visitor requests the same page in XML, [web2py](http://web2py.com) tries to find a view that can render the dictionary in XML. The developer can create views to render pages in any of the already supported protocols (HTML, XML, JSON, RSS, CSV, RTF) or additional custom protocols.
* All calls are wrapped into a transaction, and any uncaught exception causes the transaction to roll back. If the request succeeds, the transaction is committed.
* [web2py](http://web2py.com) also handles sessions and session cookies automatically, and when a transaction is committed, the session is also stored.
* It is possible to register recurrent tasks (cron) to run at scheduled times and/or after the completion of certain actions. In this way it is possible to run long and compute-intensive tasks in the background without slowing down navigation.
Here is a minimal and complete MVC application consisting of three files:
* "db.py" is the model:
db = DAL('sqlite://storage.sqlite')
db.define_table('contacts',
Field('name'),
Field('phone'))
It connects to the database (in this example a SQLite database stored in the `storage.sqlite` file) and defines a table called `contacts`. If the table does not exist, [web2py](http://web2py.com) creates it and, transparently and in the background, generates SQL code in the appropriate SQL dialect for the specific database engine used. The developer can see the generated SQL but does not need to change the code if the database back-end, which defaults to SQLite, is replaced with MySQL, PostgreSQL, MSSQL, FireBird, Oracle, DB2, Informix, or Google Big Tables in the Google App Engine.
Once a table is defined and created, [web2py](http://web2py.com) also generates a fully functional web-based database administration interface to access the database and the tables. It is called `appadmin`.
* "default.py" is the controller:
def contacts():
return dict(records=db().select(db.contacts.ALL))
In [web2py](http://web2py.com), URLs are mapped to Python modules and function calls. In this case, the controller contains a single function (or "action") called `contacts`. An action may return a string (the returned website) or a Python dictionary (a set of key:value pairs). If the function returns a dictionary, it is passed to a view with the same name as the controller/function, which in turn renders it. In this example, the function `contacts` performs a database `select` and returns the resulting records as a value associated with the dictionary key `records`.
* "default/contacts.html" is the view:
{{extend 'layout.html'}}
Records
{{for record in records:}}
{{=record.name}}: {{=record.phone}}
{{pass}}
This view is called automatically by [web2py](http://web2py.com) after the associated controller function (action) is executed. The purpose of this view is to render the variables in the returned dictionary `records=...` into HTML. The view file is written in HTML, but it embeds Python code delimited by the special `{{` and `}}` delimiters. This is quite different from the PHP code example, because the only code embedded into the HTML is "presentation layer" code. The "layout.html" file referenced at the top of the view is provided by [web2py](http://web2py.com) and constitutes the basic layout for all [web2py](http://web2py.com) applications. The layout file can easily be modified or replaced.
## Why web2py
[web2py](http://web2py.com) is one of many web application frameworks, but it has compelling and unique features. [web2py](http://web2py.com) was originally developed as a teaching tool, with the following primary motivations:
* Easy for users to learn server-side web development without compromising on functionality. For this reason [web2py](http://web2py.com) requires no installation, no configuration, has no dependencies (except for the source code distribution, which requires Python 2.5 and its standard library modules), and exposes most of its functionality via a web interface.
* [web2py](http://web2py.com) has been stable from day one because it follows a top-down design; i.e., its API was designed before it was implemented. Even as new functionality has been added, [web2py](http://web2py.com) has never broken backwards compatibility, and it will not break compatibility when additional functionality is added in the future.
* [web2py](http://web2py.com) proactively addresses the most important security issues that plague many modern web applications, as determined by [OWASP](http://www.owasp.org) below.
* [web2py](http://web2py.com) is light. Its core libraries, including the Database Abstraction Layer, the template language, and all the helpers amount to 300KB. The entire source code including sample applications and images amounts to 2.0MB.
* [web2py](http://web2py.com) has a small footprint and is very fast. It uses the [CherryPy](http://www.cherrypy.org/browser/trunk/cherrypy/wsgiserver/__init__.py) WSGI-compliant (The Web Server Gateway [Interface](http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface) ([link](http://www.python.org/dev/peps/pep-0333/)) (WSGI) is an emerging Python standard for communication between a web server and Python applications.) web server that is 30% faster than Apache with mod_proxy and four times faster than the Paste http server. Our tests also indicate that, on an average PC, it serves an average dynamic page without database access in about 10ms. The DAL has very low overhead, typically less than 3%.
## Security
The Open Web Application Security [Project](http://www.owasp.org) (OWASP) is a free and open worldwide community focused on improving the security of application software.
OWASP has listed the top ten security issues that put web applications at risk. That list is reproduced here, along with a description of how each issue is addressed by [web2py](http://web2py.com):
* "Cross Site Scripting (XSS): XSS flaws occur whenever an application takes user supplied data and sends it to a web browser without first validating or encoding that content. XSS allows attackers to execute scripts in the victim's browser which can hijack user sessions, deface web sites, possibly introduce worms, etc."
[web2py](http://web2py.com), by default, escapes all variables rendered in the view, preventing XSS.
*
"Injection Flaws: Injection flaws, particularly SQL injection, are common in web applications. Injection occurs when user-supplied data is sent to an interpreter as part of a command or query. The attacker's hostile data tricks the interpreter into executing unintended commands or changing data."
[web2py](http://web2py.com) includes a Database Abstraction Layer that makes SQL injection impossible. Normally, SQL statements are not written by the developer. Instead, SQL is generated dynamically by the DAL, ensuring that all inserted data is properly escaped.
*
"Malicious File Execution: Code vulnerable to remote file inclusion (RFI) allows attackers to include hostile code and data, resulting in devastating attacks, such as total server compromise."
[web2py](http://web2py.com) allows only exposed functions to be executed, preventing malicious file execution. Imported functions are never exposed; only actions are exposed. [web2py](http://web2py.com)'s web-based administration interface makes it very easy to keep track of what is exposed and what is not.
*
"Insecure Direct Object Reference: A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, database record, or key, as a URL or form parameter. Attackers can manipulate those references to access other objects without authorization."
[web2py](http://web2py.com) does not expose any internal objects; moreover, [web2py](http://web2py.com) validates all URLs, thus preventing directory traversal attacks. [web2py](http://web2py.com) also provides a simple mechanism to create forms that automatically validate all input values.
*
"Cross Site Request Forgery (CSRF): A CSRF attack forces a logged-on victim's browser to send a pre- authenticated request to a vulnerable web application, which then forces the victim's browser to perform a hostile action to the benefit of the attacker. CSRF can be as powerful as the web application that it attacks."
[web2py](http://web2py.com) stores all session information server side, and storing only the session id in a browser-side cookie; moreover, [web2py](http://web2py.com) prevents double submission of forms by assigning a one-time random token to each form.
*
"Information Leakage and Improper Error Handling: Applications can unintentionally leak information about their configuration, internal workings, or violate privacy through a variety of application problems. Attackers use this weakness to steal sensitive data, or conduct more serious attacks."
[web2py](http://web2py.com) includes a ticketing system. No error can result in code being exposed to the users. All errors are logged and a ticket is issued to the user that allows error tracking. Errors and source code are accessible only to the administrator.
* "Broken Authentication and Session Management: Account credentials and session tokens are often not properly protected. Attackers compromise passwords, keys, or authentication tokens to assume other users' identities."
[web2py](http://web2py.com) provides a built-in mechanism for administrator authentication, and it manages sessions independently for each application. The administrative interface also forces the use of secure session cookies when the client is not "localhost". For applications, it includes a powerful Role Based Access Control API.
*
"Insecure Cryptographic Storage: Web applications rarely use cryptographic functions properly to protect data and credentials. Attackers use weakly protected data to conduct identity theft and other crimes, such as credit card fraud."
[web2py](http://web2py.com) uses the MD5 or the HMAC+SHA-512 hash algorithms to protect stored passwords. Other algorithms are also available.
*
"Insecure Communications: Applications frequently fail to encrypt network traffic when it is necessary to protect sensitive communications."
[web2py](http://web2py.com) includes the [SSL-enabled](http://en.wikipedia.org/wiki/Secure_Sockets_Layer) CherryPy WSGI server, but it can also use Apache or Lighttpd and mod_ssl to provide SSL encryption of communications.
*
"Failure to Restrict URL Access: Frequently an application only protects sensitive functionality by preventing the display of links or URLs to unauthorized users. Attackers can use this weakness to access and perform unauthorized operations by accessing those URLs directly."
[web2py](http://web2py.com) maps URL requests to Python modules and functions. [web2py](http://web2py.com) provides a mechanism for declaring which functions are public and which require authentication and authorization. The included Role Based Access Control API allow developers to restrict access to any function based on login, group membership or group based permissions. The permissions are very granular and can be combined with CRUD to allow, for example, to give access to specific tables and/or records.
## In the box
You can download [web2py](http://web2py.com) from the official web site:
`http://www.web2py.com`
[web2py](http://web2py.com) is composed of the following components:
* **libraries**: provide core functionality of [web2py](http://web2py.com) and are accessible programmatically.
* **web server**: the CherryPy WSGI web server.
* the **admin** application: used to create, design, and manage other [web2py](http://web2py.com) applications. **admin** provide a complete web-based Integrated Development Environment (IDE) for building [web2py](http://web2py.com) applications. It also includes other functionality, such as web-based testing and a web-based shell.
* the **examples** application: contains documentation and interactive examples. **examples** is a clone of the official [web2py](http://web2py.com) web site, and includes epydoc and Sphinx documentation.
* the **welcome** application: the basic scaffolding template for any other application. By default it includes a pure CSS cascading menu and user authentication (discussed in Chapter 8).
[web2py](http://web2py.com) is distributed in source code and binary form for Microsoft Windows and for Mac OS X.
The source code distribution can be used in any platform where Python or Jython run, and includes the above-mentioned components. To run the source code, you need Python 2.5 pre-installed on the system. You also need one of the supported database engines installed. For testing and light-demand applications, you can use the SQLite database, included with Python 2.5.
The binary versions of [web2py](http://web2py.com) (for Windows and Mac OS X) include a Python 2.5 interpreter and the SQLite database. Technically, these two are not components of [web2py](http://web2py.com). Including them in the binary distributions enables you to run [web2py](http://web2py.com) out of the box.
The following image depicts the overall [web2py](http://web2py.com) structure:

## License
[web2py](http://web2py.com) is licensed under the GPL version 2 License. The full text of the license if available in ref. ([link](http://www.fsf.org/licensing/licenses/info/GPLv2.html)).
The license includes but it is not limited to the following articles:
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
[...]
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License.
[...]
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* [web2py](http://web2py.com) includes some third-party code (for example the Python interpreter, the CherryPy web server, and some JavaScript libraries). Their respective authors and licenses are acknowledged in the official [website](http://www.web2py.com) and in the code itself.
* Applications developed with [web2py](http://web2py.com), as long as they do not include [web2py](http://web2py.com) source code, are not considered derivative works. This means they are not bound by the GPLv2 license, and you can distribute the applications you developed under any license you choose, including a closed-source and/or commercial license.
## License Commercial Exception
The [web2py](http://web2py.com) license also includes a commercial exception:
You may distribute an application you developed with [web2py](http://web2py.com) together with an unmodified official binary distribution of [web2py](http://web2py.com), as downloaded from the official [website](http://www.web2py.com), as long as you make it clear in the license of your application which files belong to the application and which files belong to [web2py](http://web2py.com).
## Acknowledgments
[web2py](http://web2py.com) was originally developed by and copyrighted by Massimo Di Pierro. The first version (1.0) was released in October, 2007. Since then it has been adopted by many users, some of whom have also contributed bug reports, testing, debugging, patches, and proofreading of this book.
Some of the major contributors are, in alphabetical order by first name:
Alexandre Andrade, Alexey Nezhdanov (GAE and database performance), Alvaro Justen (dynamical translations), Andre Berthiaume, Andre Bossard, Attila Csipa (cron job), Bill Ferrett (modular DAL design), Boris Manojlovic (Ajax edit), Carsten Haese (Informix), Chris Baron, Christopher Smiga (Informix), Clifford John Lazell (tester and JS), David H. Lee (OpenID), Denes Lengyel (validators, DB2 support), Douglas Soares de Andrade (2.4 and 2.6 compliance, docstrings), Felipe Barousse, Fran Boon (authorization and authentication), Francisco Gama (bug fixing), Fred Yankowski (XHTML compliance), Gabriele Carrettoni, Graham Dumpleton, Gregor Jovanovich, Hans Christian v. Stockhausen (OpenID), Hans Donner (GAE support, Google login, widgets, Sphinx documentation), Ivan Valev, Joe Barnhart, Jonathan Benn (validators and tests), Jonathan Lundell, Jose Jachuf (Firebird support), Kacper Krupa, Kyle Smith (JavaScript), Limodou (winservice), Lucas Geiger,Marcel Leuthi (Oracle support), Mark Larsen (taskbar widget), Mark Moore (databases and daemon scripts), Markus Gritsch (bug fixing), Martin Hufsky (expressions in DAL), Mateusz Banach (stickers, validators, contenttype), Michael Willis (shell), Milan Andric, Minor Gordon, Nathan Freeze (admin design, validators), Niall Sweeny (MSSQL support), Niccolo Polo (epydoc), Nicolas Bruxer (memcache support), Ondrej Such (MSSQL support), Pai (internationalization), Phyo Arkar Lwin (web hosting and Jython tester), Ricardo Cardenes, Richard Gordon, Richard Baron Penman, Robin Bhattacharyya (Google App Engine support), Roman Goldmann, Ruijun Luo (windows binary), Scott Santarromana, Sergey Podlesnyi (Oracle and migrations tester), Shane McChesney, Sharriff Aina (tester and PyAMF integration), Sterling Hankins (tester), Stuart Rackham (MSSQL support), Telman Yusupov (Oracle support), Tim Farrell, Tim Michelsen (Sphinx documentation), Timothy Farrell (Python 2.6 compliance, windows support), Tito Garrido, Yair Eshel (internationalizaiton), Yarko Tymciurak (design, Sphinx documentation), Ygao, Younghyun Jo (internationalization), Zoom Quiet
I am sure I forgot somebody, so I apologize.
I particularly thank Alvaro, Denes, Felipe, Graham, Jonathan, Hans, Kyle, Mark, Richard, Robin, Roman, Scott, Shane, Sharriff, Sterling, Stuart and Yarko for proofreading various chapters of this book. Their contribution was invaluable. If you find any errors in this book, they are exclusively my fault, probably introduced by a last-minute edit. I also thank Ryan Steffen of Wiley Custom Learning Solutions for help with publishing the first edition of this book.
[web2py](http://web2py.com) contains code from the following authors, whom I would like to thank:
Guido van Rossum for [Python](http://www.python.org), Peter Hunt, Richard Gordon, Robert Brewer for the [CherryPy](http://www.cherrypy.org) web server, Christopher Dolivet for [EditArea](http://www.cdolivet.net/editarea/), Brian Kirchoff for [nicEdit](http://nicedit.com/), Bob Ippolito for [simplejson](http://pypi.python.org/pypi/simplejson), Simon Cusack and Grant Edwards for [pyRTF](http://pyrtf.sourceforge.net/), Dalke Scientific Software for [pyRSS2Gen](http://www.dalkescientific.com/Python/PyRSS2Gen.html), Mark Pilgrim for [feedparser](http://www.feedparser.org/), Trent Mick for [markdown2](http://code.google.com/p/python-markdown2/), Allan Saddi for fcgi.py, Evan Martin for the Python memcache [module](http://www.tummy.com/Community/software/python-memcached/), John Resig for [jQuery](http://jquery.com/).
The logo used on the cover of this book was designed by Peter Kirchner at Young Designers.
I thank Helmut Epp (provost of DePaul University), David Miller (Dean of the College of Computing and Digital Media of DePaul University), and Estia Eichten (Member of MetaCryption LLC), for their continuous trust and support.
Finally, I wish to thank my wife, Claudia, and my son, Marco, for putting up with me during the many hours I have spent developing [web2py](http://web2py.com), exchanging emails with users and collaborators, and writing this book. This book is dedicated to them.
## About this Book
This book includes the following chapters, besides this introduction:
* Chapter 2 is a minimalist introduction to Python. It assumes knowledge of both procedural and object-oriented programming concepts such as loops, conditions, function calls and classes, and covers basic Python syntax. It also covers examples of Python modules that are used throughout the book. If you already know Python, you may skip Chapter 2.
* Chapter 3 shows how to start [web2py](http://web2py.com), discusses the administrative interface, and guides the reader through various examples of increasing complexity: an application that returns a string, a counter application, an image blog, and a full blown wiki application that allows image uploads and comments, provides authentication, authorization, web services and an RSS feed. While reading this chapter, you may need to refer to Chapter 2 for general Python syntax and to the following chapters for a more detailed reference about the functions that are used.
* Chapter 4 covers more systematically the core structure and libraries: URL mapping, request, response, sessions, cacheint, CRON, internationalization and general workflow.
* Chapter 5 is a reference for the template language used to build views. It shows how to embed Python code into HTML, and demonstrates the use of helpers (objects that can generate HTML).
* Chapter 6 covers the Database Abstraction Layer, or DAL. The syntax of the DAL is presented through a series of examples.
* Chapter 7 covers forms, form validation and form processing. FORM is the low level helper for form building. SQLFORM is the high level form builder. In Chapter 7 we also discuss the new Create/Read/Update/Delete (CRUD) API.
* Chapter 8 covers authentication, authorization and the extensible Role-Based Access Control mechanism available in [web2py](http://web2py.com). Mail configuration and CAPTCHA are also discussed here, since they are used by authentication.
* Chapter 9 is about creating web services in [web2py](http://web2py.com). We provide examples of integration with the Google Web Toolkit via Pyjamas, and with Adobe Flash via PyAMF.
* Chapter 10 is about [web2py](http://web2py.com) and jQuery recipes. [web2py](http://web2py.com) is designed mainly for server-side programming, but it includes jQuery, since we have found it to be the best open-source JavaScript library available for effects and Ajax. In this chapter, we discuss how to effectively use jQuery with [web2py](http://web2py.com).
* Chapter 11 is about production deployment of [web2py](http://web2py.com) applications. We mainly address three possible production scenarios: on a Linux web server or a set of servers (which we consider the main deployment alternative), running as a service on a Microsoft Windows environment, and deployment on the Google Applications Engine (GAE). In this chapter, we also discuss security and scalability issues.
* Chapter 12 contains a variety of other recipes to solve specific tasks, including upgrades, geocoding, pagination, Twitter API, and more.
This book only covers basic [web2py](http://web2py.com) functionalities and the API that ships with [web2py](http://web2py.com). This book does not cover [web2py](http://web2py.com) appliances, for example KPAX, the [web2py](http://web2py.com) Content Management System. The appliance for Central Authentication Service is briefly discussed in Chapter 8.
You can download [web2py](http://web2py.com) appliances from the corresponding web [site](http://www.web2py.com/appliances).
You can find additional topics discussed on [AlterEgo](http://www.web2py.com/AlterEgo), the interactive [web2py](http://web2py.com) FAQ.
## Elements of Style
Ref. ([link](http://www.python.org/dev/peps/pep-0008/)) contains good style practices when programming with Python. You will find that [web2py](http://web2py.com) does not always follow these rules. This is not because of omissions or negligence; it is our belief that the users of [web2py](http://web2py.com) should follow these rules and we encourage it. We chose not to follow some of those rules when defining [web2py](http://web2py.com) helper objects in order to minimize the probability of name conflict with objects defined by the user.
For example, the class that represents a `` is called `DIV`, while according to the Python style reference it should have been called `Div`. We believe that, for this specific example that using an all-upper-case "DIV" is a more natural choice. Moreover, this approach leaves programmers free to create a class called "Div" if they choose to do so. Our syntax also maps naturally into the DOM notation of most browsers (including, for example, Firefox).
According to the Python style guide, all-upper-case strings should be used for constants and not variables. Continuing with our example, even considering that `DIV` is a class, it is a special class that should never be redefined by the user because doing so would break other [web2py](http://web2py.com) applications. Hence, we believe this qualifies the `DIV` class as something that should be treated as a constant, further justifying our choice of notation.
In summary, the following conventions are followed:
* HTML helpers and validators are all upper case for the reasons discussed above (for example `DIV`, `A`, `FORM`, `URL`).
* The translator object `T` is upper case despite the fact that it is an instance of a class and not a class itself. Logically the translator object performs an action similar to the HTML helpers --- it affects rendering part of the presentation. Also, `T` needs to be easy to locate in the code and has to have a short name.
* DAL classes follow the Python style guide (first letter capitalized), sometimes with the addition of a clarifying DAL prefix (for example `Table`, `Field`, `DALQuery`, etc.).
In all other cases we believe we have followed, as much as possible, the Python Style Guide (PEP8). For example all instance objects are lower-case (request, response, session, cache), and all internal classes are capitalized.
In all the examples of this book, [web2py](http://web2py.com) keywords are shown in bold, while strings and comments are shown in italic.