Restrictions on registration

If you want to allow visitors to register but not to log in until registration has been approved by the administrator You can approve a registration via the appadmin interface. Look into the table auth_user. Pending registrations have a registration_key field set to pending. A registration is approved when this field is set to blank. Via the appadmin interface, you can also block a user from logging in. Locate the user in the table auth_user and set the registration_key to blocked. blocked...

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

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

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

Response

Response is another instance of the Storage class. It contains the following response.author optional parameter that may be included in the views. It should contain the name of the author of the page being displayed and should be rendered by the HTML meta tag. response.body a stringio object into which web2py writes the output page body. NEVER CHANGE THIS VARIABLE. response.cookies similar to request.cookies, but while the latter contains the cookies sent from the client to the server, the...

CSV all tables at once

In web2py, you can backup restore an entire database with two commands To export This mechanism can be used even if the importing database is of a different type than the exporting database. The data is stored in somefile.csv as a CSV file where each table starts with one line that indicates the tablename, and another line with the fieldnames Two tables are separated by 5 r n r n. The file ends with the line The file does not include uploaded files if these are not stored in the database. In...

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

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

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

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

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

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

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

HTTP and redirect

Web2py defines only one new exception called http. This exception can be raised anywhere in a model, a controller, or a view with the command 1 raise HTTP 400, my message It causes the control flow to jump away from the user's code, back to web2py, and return an HTTP response like 2 Date Sat, 05 Jul 2008 19 36 22 GMT 3 Server CherryPy 3.1.0beta3 WSGI Server The first argument of http is the HTTP status code. The second argument is the string that will be returned as the body of the response....

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

Authorization and CRUD

Using decorators and or explicit checks provides one way to implement access control. Another way to implement access control is to always use CRUD as opposed to SQLFORM to access the database and to ask CRUD to enforce access control on database tables and records. This is done by linking Auth and CRUD with the following statement This will prevent the visitor from accessing any of the CRUD functions unless the visitor is logged in and has explicit access. For example, to allow a visitor to...

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

Renaming Auth tables

The actual names of the Auth tables are stored in 1 auth.settings.table_user_name 'auth_user' 'auth_group' 'auth_membership' 'auth_permission' 'auth_event' The names of the table can be changed by reassigning the above variables after the auth object is defined and before the Auth tables are defined. For example 2 auth.settings.table_user_name 'person' The actual tables can also be referenced, independently of their actual names, by

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

Setup Apache and modwsgi on Windows

Installing Apache, and mod_wsgi under Windows requires a different procedure. Here are assuming Python 2.5 is installed, you are running from source and web2py is located at c web2py. First download the requires packages Apache apache_2 . 2 .11-Win32 -x8 6 -openssl- 0 . 9 . 8i .ms i from 1 1 mod_wsgi_py2 5_apache22 mod_wsgi.so Second, run apache. . .ms i and follow the wizard screens. On the server information screen Second, run apache. . .ms i and follow the wizard screens. On the server...

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