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

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

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

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

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

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

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

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

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

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

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