Grouping and Counting

When doing joins, sometimes you want to group rows according to certain criteria and count them. For example, count the number of dogs owned by every person. web2py allows this as well. First, you need a count operator. Second, you want to join the person table with the dog table by owner. Third, you want to select all rows person dog , group them by person, and count them while grouping 1 gt gt gt count db.person.id.count 2 gt gt gt for row in 3 print row.person.name, row._extra count Notice...

The ajax Function

In web2py_ajax.html, web2py defines a function called ajax which is based on, but should not be confused with, the jQuery function . aj ax. The latter is much more powerful than the former, and for its usage, we refer you to ref. 31 and ref. 68 . However, the former function is sufficient for many complex tasks, and is easier to use. The ajax function is a JavaScript function that has the following syntax 1 ajax url, id1, id2, , target It asynchronously calls the url first argument , passes the...

Builtin Helpers

A This helper is used to build links. 1 gt gt gt print A ' lt click gt ', XML ' lt b gt me lt b gt ' , 3 lt a B This helper makes its contents bold. 1 gt gt gt print B ' lt hello gt ', XML ' lt i gt world lt i gt ' , _class 'test', _id 0 2 lt b id 0 BODY This helper makes the body of a page. 1 gt gt gt print BODY ' lt hello gt ', XML ' lt b gt world lt b gt ' , _bgcolor 'red' 2 lt body bgcolor CENTER This helper centers its content. 1 gt gt gt print CENTER ' lt hello gt ', XML ' lt b gt world...

Exporting and Importing Data CSV one table at a time

When a DALRows object is converted to a string it is automatically serialized in CSV 1 gt gt gt rows You can serialize a single table in CSV and store it in a file test.csv 1 gt gt gt open 'test.csv1, 'w' and you can easily read it back with When importing, web2py looks for the field names in the CSV header. In this example, it finds two columns person.id and person.name. It ignores the person. prefix, and it ignores the id fields. Then all records are appended and assigned new ids. Both of...

Basic Validators

IS_ALPHANUMERIC This validator checks that a field value contains only characters in the ranges a-z, A-Z, or 0-9. 1 requires IS_ALPHANUMERIC error_message T 'must be alphanumeric ' IS.DATE This validator checks that a field value contains a valid date in the specified format. It is good practice to specify the format using the translation operator, in order to support different formats in different locales. 1 requires IS_DATE format T ' Y- m- d' , 2 error_message T 'must be YYYY-MM-DD ' For the...

Voting and Rating

Another Ajax application is voting or rating items in a page. Here we consider an application that allows visitors to vote on posted images. The application consists of a single page that displays the images sorted according to their vote. We will allow visitors to vote multiple times, although it is easy to change this behavior if visitors are authenticated, by keeping track of the individual votes in the database and associating them with the request.env.remote addr of the voter. 1 db DAL...

T and Internationalization

The object T is the language translator. It constitutes a single global instance of the WEB2PY class gluon.language.translator. All string constants and only string constants should be marked by T, for example Strings that are marked with t are identified by web2py as needing language translation and they will be translated when the code in the model, controller, or view is executed. If the string to be translated is not a constant but a variable, it will be added to the translation file at...

Startup

Web2py comes in binary packages for Windows and Mac OS X. There is also a source code version that runs on Windows, Mac, Linux, and other Unix systems. The Windows and OS X binary versions include the necessary Python interpreter. The source code package assumes that Python is already installed on the computer. web2py requires no installation. To get started, unzip the downloaded zip file for your specific operating system and execute the corresponding web2py file. On Unix and Linux, run from...

Sqlform and uploads

Grid Sqlform Grid Web2py

They are rendered as INPUT fields of type file. Unless otherwise specified, the uploaded file is streamed in using a buffer, and stored under the uploads folder of the application using a new safe name, assigned automatically. The name of this file is then saved into the field of type uploads. As an example, consider the following model 2 Field 'name' , requires IS_NOT_EMPTY , You can use the same controller action display_form shown above. When you insert a...

Web2py Url Vars

The url function is one of the most important functions in web2py. It generates internal URL paths for the actions and the static files. Here is an example Notice that the output of the URL function depends on the name of the current application, the calling controller and other parameters. web2py supports URL mapping and reverse URL mapping. URL mapping allows to redefine the format of external URLs. If you use the URL function to generate all the internal URLs, then additions or changes to...

Upload Files in Database

By default, all uploaded files handled by SQLFORMs are safely renamed and stored in the filesystem under the uploads folder. It is possible to instruct web2py to store uploaded files in the database instead. where dog. image is of type upload. To make the uploaded image go in the same record as the name of the dog, you must modify the table definition by adding a blob field and link it to the upload field 3 Field 'image', 'upload', uploadfield 'image_data' , 4 Field 'image_data', 'blob' Here...

Web2py Xml Helper

XML is an object used to encapsulate text that should not be escaped. The text may or may not contain valid XML. For example, it could contain JavaScript. The text in this example is escaped 1 gt gt gt print DIV by using XML you can prevent escaping 1 gt gt gt print Sometimes you want to render HTML stored in a variable, but the HTML may contain unsafe tags such as scripts 1 gt gt gt print XML ' lt script gt ' 2 lt script gt alert unsafe lt script gt Unescaped executable input such as this for...

URL Rewrite

Web2py has the ability to rewrite the URL path of incoming requests prior to calling the controller action URL mapping , and conversely, web2py can rewrite the URL path generated by the url function reverse URL mapping . One reason to do this is for handling legacy URLs, another is to simplify paths and make them shorter. To use this feature, create a new file in the web2py folder called routes.py and define two lists or tuples of 2-tuples routes.in and routes.out. Each tuple contains two...

Migrations

Web2py Admin

We refer to this behavior as a migration. web2py logs all migrations and migration attempts in the file databases sql.log. The first argument of define.tabie is always the table name. The other unnamed arguments are the fields Field . The function also takes an optional last argument called migrate which must be referred to explicitly by name as in 1 gt gt gt db.define_table 'person', Field 'name' , migrate 'person.table' The value of migrate is the filename in the databases folder for the...

Web2py Wiki Markdown

The visitor will be able to create pages, search them by title , and edit them. The visitor will also be able to post comments exactly as in the previous applications , and also post documents as attachments to the pages and link them from the pages. As a convention, we adopt the Markdown syntax for our wiki syntax. We will also implement a search page with Ajax, an RSS feed for the pages, and a handler to search the pages via XML-RPC 44 . The following diagram...

Web2py Cache View

Cache a global object also available in the web2py execution environment. It has two attributes cache.ram the application cache in main memory. cache.disk the application cache on disk. cache is callable, this allows it to be used as a decorator for caching actions and views. The following example caches the time.ctime function in RAM 3 t cache.ram 'time', lambda time.ctime , time_expire 5 4 return dict time t, link A 'click me', _href request.url The output of lambda time.ctime is cached in...

Web2py Cron Example

The web2py cron provides the ability for applications to execute tasks at preset times, in a platform independent manner. For each application, cron functionality is defined by a crontab file ap-p cron crontab, following the syntax defined here with some extensions that was web2py specific 1 This means that every application can have a separate cron configuration and that cron config can be changed from within web2py without affecting the host OS itself. 1 0-59 1 root python path to python...

Simplejson

Web2py includes gluon.contrib.simplejson, developed by Bob Ippolito. This module provides the most standard Python-JSON encoder-decoder. SimpleJSON consists of two functions gluon.contrib. simplesj son.dumps a encodes a Python object a into gluon.contrib.simplej son.loads b decodes a JavaScript object b into a Python object. Object types that can be serialized include primitive types, lists, and dictionaries. Compound objects can be serialized with the exception of user defined classes. Here is...

Alternate Login Methods

Auth provides multiple login methods and hooks to create new login methods. Each supported login method corresponds to a file in the folder Refer to the documentation in the files themselves for each login method, but here we provide some examples. First of all we need to make a distinction between two types of alternate login methods login methods that use a web2py form although the credentials are verified outside web2py . An example is LDAP. login methods that require an external sign-on...

Insert UpdateDelete Sqlform

If you pass a record as optional second argument to the sqlform constructor, the form becomes an UPDATE form for that record. This means that when the form is submitted the existing record is updated and no new record is inserted. If you set the argument deletable True, the UPDATE form displays a check to delete checkbox. If checked, the record is deleted. You can, for example, modify the controller of the previous example so that when we pass an additional integer argument in the URL path, as...

Sqlform

We now move to the next level by providing the application with a model file 3 Field 'name', requires IS_NOT_EMPTY 3 if form.accepts request.vars, session 4 response.flash 'form accepted' 6 response.flash 'form has errors' 8 response.flash 'please fill out the form' The view does not need to be changed. In the new controller, you do not need to build a FORM, since the SQLFORM constructor built one from the table db.person defined in the model. This new form, when serialized, appears as 1 lt...

An Image Blog

Define Table Pic

Here, as another example, we wish to create a web application that allows the administrator to post images and give them a name, and allows the visitors of the web site to view the images and submit comments. As before, create the new application from the site page in admin and navigate to the EDIT page We start by creating a model, a representation of the persistent data in the application the images to upload, their names, and the comments . First, you need to create edit a model file which,...

Central Authentication Service

Cas Login Page

Web2py provides support for authentication and authorization via appliances. Here we discuss the cas appliance for Central Authentication Service CAS . Notice that at the time of writing CAS is distict and does not work with Auth. This will change in the future. CAS is an open protocol for distributed authentication and it works in the following way When a visitor arrives at our web site, our application check in the session if the user is already authenticated for example via a session. token...

Remote Procedure Calls

Web2py provides a mechanism to turn any function into a web service. The mechanism described here differs from the mechanism described before because The function may take arguments The function may be defined in a model or a module instead of controller You may want to specify in detail which RPC method should be supported It enforces a more strict URL naming convention It is smarter then the previous methods because it works for a fixed set of protocols. For the same reason it is not as...

Page Layout

Views can extend and include other views in a tree-like structure, as in the following example an upward arrow means extend, while a downward arrow means include header.html index.html sidebar.html footer.html header.html index.html sidebar.html footer.html In this example, the view index.html extends layout.html and includes body.html. layout.html includes header.html, sidebar.html and footer.html. The root of the tree is what we call a layout view. Just like any other HTML template file, you...

PyRTF

Another common need of web sites is that of generating Word-readable text documents. The simplest way to do so is using the Rich Text Format RTF document format. This format was invented by Microsoft and it has since become a standard. web2py includes gluon.contrib.pyrtf, developed by Simon Cusack and revised by Grant Edwards. This module allows you to generate RTF documents programmatically including colored formatted text and pictures. In the following example we instantiate two basic RTF...

Amfrpc

AMFRPC is the Remote Procedure Call protocol used by Flash clients to communicate with a server. web2py supports AMFRPC but it requires that you run web2py from source and that you preinstall the PyAMF library. This can be installed from the Linux or Windows shell by typing please consult the PyAMF documentation for more details . In this subsection we assume that you are already familiar with Action-Script programming. We will create a simple service that takes two numerical values, adds them...

Multiple forms per page

The content of this section applies to both form and sqlform objects. It is possible to have multiple forms per page, but you must allow web2py to distinguish them. If these are derived by sqlform from different tables, then web2py gives them different names automatically otherwise you need to explicitly give them different form names. Moreover, when multiple forms are present on the same page, the mechanism for preventing double submission breaks, and you must omit the session argument when...

Settings and Messages

Here is a list of all parameters that can be customized for Auth 1 auth.settings.actions_disabled The actions that should be disabled, for example 'register' . Set to True so that registrants receive a verification email and are required to click a link to complete registration. Set to True to prevent login of newly registered users until they are approved this is done by setting registration_key ' ' via appadmin or programmati-cally . 1 auth.settings.create_user_groups True Set to False if you...

Access Control

Web2py includes a powerful and customizable Role-Based Access Control RBAC mechanism. Here is a definition from Wikipedia Role-Based Access Control RBAC is an approach to restricting system access to authorized users. It is a newer alternative approach to mandatory access control MAC and discretionary access control DAC . RBAC is sometimes referred to as role-based security. RBAC is a policy neutral and flexible access control technology sufficiently powerful to simulate DAC and MAC....

Web2py Form Action

Consider as an example a test application with the following default.py controller and the associated default display_form.html view 2 lt h2 gt Input form lt h2 gt 3 form enctype multipart form-data method post gt 6 lt input name name gt 7 lt input type 'submit gt 9 lt h2 gt Submitted variables lt h2 gt 10 BEAUTIFY request .vars This is a regular HTML form that asks for the user's name. When you fill the form and click the submit button, the form self-submits, and the variable request.vars.name...

Start as Linux Daemon

Unless you are using mocLwsgi, you should setup the web2py server so that it can be started stopped restarted as any other Linux daemon, and so it can start automatically at the computer boot stage. The process to set this up is specific to various Linux Unix distributions. In the web2py folder, there are two scripts which can be used for this purpose On Ubuntu and other Debian-based Linux distributions, edit the script web2py.ubuntu.sh and replace the usr lib web2py path with the path of your...

Setup PostgreSQL

PostgreSQL is a free and open source database which is used in demanding production environments, for example, to store the .org domain name database, and has been proven to scale well into hundreds of terabytes of data. It has very fast and solid transaction support, and provides an auto-vacuum feature that frees the administrator from most database maintenance tasks. On an Ubuntu or other Debian-based Linux distribution, it is easy to install PostgreSQL and its Python API with 1 sudo apt-get...

Conditional Fields in Forms

A typical application of jQuery effects is a form that changes its appearance based on the value of its fields. This is easy in web2py because the SQLFORM helper generates forms that are CSS friendly. The form contains a table with rows. Each row contains a label, an input field, and an optional third column. The items have ids derived strictly from the name of the table and names of the fields. The convention is that every INPUT field has a name equal to table-name Jieldname and is contained...

Google App Engine

It is possible to run web2py code on Google App Engine GAE 12 , including DAL code, with some limitations. The GAE platform provides several advantages over normal hosting solutions Ease of deployment. Google completely abstracts the underlying architecture. Scalability. Google will replicate your app as many times as it takes to serve all concurrent requests BigTable. On GAE, instead of a normal relational database, you store persistent information in BigTable, the datastore Google is famous...

Authorization

Once a new user is registered, a new group is created to contain the user. The role of the new user is conventionally user_ id where id is the id of the newly created id. The creation of the group can be disabled with 1 auth.settings.create_user_groups False although we do not suggest doing so. Users have membership in groups. Each group is identified by a name role. Groups have permissions. Users have permissions because of the groups they belong to. You can create groups, give membership and...

Start as Windows Service

What Linux calls a daemon, Windows calls a service. The web2py server can easily be installed started stopped as a Windows service. In order to use web2py as a Windows service, you must create a file options.py with startup parameters 5 pid_filename 'httpserver.pid' 6 log_filename 'httpserver.log' 10 server_name socket.gethostname You don't need to create options.py from scratch since there is already an options_std.py in the web2py folder that you can use as a model. After creating options.py...

Command Line Options

It is possible to skip the GUI and start web2py directly from the command line by typing something like 1 python web2py.py -a 'your password' -i 127.0.0.1 -p 8000 When web2py starts, it creates a file called parameters_8000.py where it stores the hashed password. If you use lt ask gt as the password, web2py prompts you for it. For additional security, you can start web2py with 1 python web2py.py -a ' lt recycle gt ' -i 127.0.0.1 -p 8000 In this case web2py reuses the previously stored hashed...

URL Mapping

To the function f in controller c.py in application a. If f is not present, web2py defaults to the index controller function. If c is not present, web2py defaults to the default.py controller, and if a is not present, web2py defaults to the init application. If there is no init application, web2py tries to run the welcome application. This is shown schematically in the image below By default, any new request also creates a new session. In addition, a session cookie is returned to the client...

Jsonrpc

JSONRPC is very similar to XMLRPC, but uses the JSON based protocol to encode the data instead of XML. As an example of application here, we discuss its usage with Pyjamas. Pyjamas is a Python port of the Google Web Toolkit originally written in Java . Pyjamas allows to write a client application in Python. Pyjamas translates this code into JavaScript. web2py serves the javascript and communicates with it via AJAX requests originating from the client and triggered by user actions. Here we...

Report Lab and PDF

Web2py can also generate PDF documents, with an additional library called ReportLab 66 . If you are running web2py from source, it is sufficient to have ReportLab installed. If you are running the Windows binary distribution, you need to unzip ReportLab in the web2py folder. If you are running the Mac binary distribution, you need to unzip ReportLab in the folder From now on we assume ReportLab is installed and that web2py can find it. We will create a simple action called get_me_a_pdf that...

Layout Builder

The web2py web site provides a layout builder to help us design new layout pages. Here is a screenshot This is a SubSubHeader lilis is a SubSiibSiibHeader This app is based oil the work of From Wikipedia In the mid igoo's, Johannes Itten developed a new kind of color changed the way color was seen, influencing artists and designers right up to t moment. The Bauhaus in Weimar, Germany was home to many artists whose influ felt today in the worlds of art and design. It was there that Itten...

Twitter API

Here are some quick examples on how to post get tweets. No third-party libraries are required, since Twitter uses simple RESTful APIs. Here is an example of how to post a tweet 1 def 2 import urllib, urlib2, base64 3 import gluon.contrib.simplejson as sj 4 args 6 headers 'Authorization' 'Basic ' base64.b64encode username ' ' 7 request 8 return Here is an example of how to receive tweets 4 import gluon.contrib.simplejson as sj 6 tweets XML sj.loads page ' timeline' For more complex operations,...

Captcha and reCAPTCHA

To prevent spammers and bots registering on your site, you may require a registration CAPTCHA. web2py supports reCAPTCHA 65 out of the box. This is because reCAPTCHA is very well designed, free, accessible it can read the words to the visitors , easy to set up, and does not require installing any third-party libraries. This is what you need to do to use reCAPTCHA Register with reCAPTCHA 65 and obtain a PUBLIC_KEY, PRI-VATE_KEY couple for your account. These are just two strings. Append the...

Import Other Modules

Web2py is written in Python, so it can import and use any Python module, including third party modules. It just needs to be able to find them. Modules can be installed in the official Python site-packages directory or anywhere your application can find them. Modules in site-packages directory are, as the name suggests, site-level packages. Applications requiring site-packages are not portable unless these modules are installed separately. The advantage of having modules in site-packages is that...

Deployment Recipes

There are multiple ways to deploy web2py in a production environment the details depend on the configuration and the services provided by the host. In this chapter we consider the following issues Configuration of production-quality web servers Apache, Lighttpd, Cherokee Deployment on the Google App Engine GAE 12 web2py comes with an SSL 20 enabled web server, the CherryPy ws-giserver 21 . While this is a fast web server, it has limited configuration capabilities. For this reason it is best to...

Setup mocLwsgi on Linux

Download and unzip web2py source on the machine where you installed the web server above. Install web2py under users www-data , for example, and give ownership to user www-data and group www-data. These steps can be performed with the following shell commands 2 sudo wget 4 sudo chown -R www-data www-data user www-data web2py To set up web2py with mod_wsgi, create a new Apache configuration file 1 etc apache2 sites-available web2py 2 ServerName web2py.example.com 3 WSGIDaemonProcess web2py user...