segunda-feira, 20 de maio de 2013


def isprime(number):
    for p in range(2, number):
        if (number % p) == 0:
            return False
    return True
"Python functions, created with either def or lambda 
allow re-factoring existing functions in terms of a different 
set of arguments. cache.ram and cache.disk 
are web2py caching functions. "
Web2py help 


This is a very powerful module. It provides functions that can serialize almost any Python object, including self-referential objects. For example, let's build a weird object:
>>> class MyClass(object): pass >>> myinstance = MyClass() >>> myinstance.x = 'something' >>> a = [1 ,2, {'hello':'world'}, [3, 4, [myinstance]]]and now:
>>> import cPickle >>> b = cPickle.dumps(a) >>> c = cPickle.loads(b)In this example, b is a string representation of a, and c is a copy of a generated by de-serializing b.
cPickle can also serialize to and de-serialize from a file:
>>> cPickle.dump(a, open('myfile.pickle', 'wb')) >>> c = cPickle.load(open('myfile.pickle', 'rb'))
More details in>: 
Next chapter: 

Chapter Table of Contents



web2py comes in binary packages for Windows and Mac OS X. They include the Python interpreter so you do not need to have it pre-installed. There is also a source code version that runs on Windows, Mac, Linux, and other Unix systems. 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 (source distribution), run:
On OS X (binary distribution), run:
On Windows (binary web2py distribution), run:
On Windows (source web2py distribution), run:
c:/Python27/python.exe web2py.exe
Attention, to run web2py on Windows from source you must install first Mark Hammond's win32 extensions from
The web2py program accepts various command line options which are discussed later.
By default, at startup, web2py displays a startup window and then displays a GUI widget that asks you to choose a one-time administrator password, the IP address of the network interface to be used for the web server, and a port number from which to serve requests. By default, web2py runs its web server on (port 8000 on localhost), but you can run it on any available IP address and port. You can query the IP address of your network interface by opening a command line and typing ipconfig on Windows or ifconfig on OS X and Linux. From now on we assume web2py is running on localhost ( Use to run web2py publicly on any of your network interfaces.
If you do not provide an administrator password, the administration interface is disabled. This is a security measure to prevent publicly exposing the admin interface.
The administrative interface, admin, is only accessible from localhost unless you run web2py behind Apache with mod_proxy. If admin detects a proxy, the session cookie is set to secure and admin login does not work unless the communication between the client and the proxy goes over HTTPS; this is a security measure. All communications between the client and admin must always be local or encrypted; otherwise an attacker would be able to perform a man-in-the middle attack or a replay attack and execute arbitrary code on the server.
After the administration password has been set, web2py starts up the web browser at the page:
If the computer does not have a default browser, open a web browser and enter the URL.
Clicking on "administrative interface" takes you to the login page for the administration interface.
The administrator password is the password you chose at startup. Notice that there is only one administrator, and therefore only one administrator password. For security reasons, the developer is asked to choose a new password every time web2py starts unless the option is specified. This is distinct from the authentication mechanism in web2py applications.
After the administrator logs into web2py, the browser is redirected to the "site" page.
This page lists all installed web2py applications and allows the administrator to manage them. web2py comes with three applications:
  • An admin application, the one you are using right now.
  • An examples application, with the online interactive documentation and a replica of the web2py official website.
  • A welcome application. This is the basic template for any other web2py application. It is referred to as the scaffolding application. This is also the application that welcomes a user at startup.
Ready-to-use web2py applications are referred to as web2py appliances. You can download many freely available appliances from [appliances] . web2py users are encouraged to submit new appliances, either in open-source or closed-source (compiled and packed) form.
From the admin application's site page, you can perform the following operations:
  • install an application by completing the form on the bottom right of the page. Give a name to the application, select the file containing a packaged application or the URL where the application is located, and click "submit".
  • uninstall an application by clicking the corresponding button. There is a confirmation page.
  • create a new application by choosing a name and clicking "create".
  • package an application for distribution by clicking on the corresponding button. A downloaded application is a tar file containing everything, including the database. You should not untar this file; it is automatically unpackaged by web2py when installed with admin.
  • clean up an application's temporary files, such as sessions, errors and cache files.
  • enable/disable each application. When an application is disabled it cannot be called remotely but it is not disabled form localhost. This means disabled applications can still be accessed behind a proxy. An application is disabled by creating a file called "DISABLED" in the application folder. Users who try to access a disabled application will receive a 503 HTTP error. You can use routes_onerror to customize the error page.
  • EDIT an application.
When you create a new application using admin, it starts as a clone of the "welcome" scaffolding app with a "models/" that creates a SQLite database, connects to it, instantiates Auth, Crud, and Service, and configures them. It also provides a "controller/" which exposes actions "index", "download", "user" for user management, and "call" for services. In the following, we assume that these files have been removed; we will be creating apps from scratch.
web2py also comes with a wizard, described later in this chapter, that can write an alternate scaffolding code for you based on layouts and plugins available on the web and based on high level description of the models.

Simple examples

Say hello

Here, as an example, we create a simple web app that displays the message "Hello from MyApp" to the user. We will call this application "myapp". We will also add a counter that counts how many times the same user visits the page.
You can create a new application simply by typing its name in the form on the top right of the site page in admin.
After you press [create], the application is created as a copy of the built-in welcome application.
To run the new application, visit:
Now you have a copy of the welcome application.
To edit an application, click on the edit button for the newly created application.
The edit page tells you what is inside the application. Every web2py application consists of certain files, most of which fall into one of six categories:
  • models: describe the data representation.
  • controllers: describe the application logic and workflow.
  • views: describe the data presentation.
  • languages: describe how to translate the application presentation to other languages.
  • modules: Python modules that belong to the application.
  • static files: static images, CSS files[css-w,css-o,css-school] , JavaScript files[js-w,js-b] , etc.
  • plugins: groups of files designed to work together.
Everything is neatly organized following the Model-View-Controller design pattern. Each section in the edit page corresponds to a subfolder in the application folder.
Notice that clicking on section headings will toggle their content. Folder names under static files are also collapsible.
Each file listed in the section corresponds to a file physically located in the subfolder. Any operation performed on a file via the admin interface (create, edit, delete) can be performed directly from the shell using your favorite editor.
The application contains other types of files (database, session files, error files, etc.), but they are not listed on the edit page because they are not created or modified by the administrator; they are created and modified by the application itself.
The controllers contain the logic and workflow of the application. Every URL gets mapped into a call to one of the functions in the controllers (actions). There are two default controllers: "" and "". appadmin provides the database administrative interface; we do not need it now. "" is the controller that you need to edit, the one that is called by default when no controller is specified in the URL. Edit the "index" function as follows:
def index():
    return "Hello from MyApp"
Here is what the online editor looks like:
Save it and go back to the edit page. Click on the index link to visit the newly created page.
When you visit the URL
the index action in the default controller of the myapp application is called. It returns a string that the browser displays for us. It should look like this:
Now, edit the "index" function as follows:
def index():
    return dict(message="Hello from MyApp")
Also from the edit page, edit the view "default/index.html" (the view file associated with the action) and completely replace the existing contents of that file with the following:



Now the action returns a dictionary defining a message. When an action returns a dictionary, web2py looks for a view with the name
and executes it. Here [extension] is the requested extension. If no extension is specified, it defaults to "html", and that is what we will assume here. Under this assumption, the view is an HTML file that embeds Python code using special {{ }} tags. In particular, in the example, the {{=message}} instructs web2py to replace the tagged code with the value of the message returned by the action. Notice that message here is not a web2py keyword but is defined in the action. So far we have not used any web2py keywords.
If web2py does not find the requested view, it uses the "generic.html" view that comes with every application.
Mac Mail
Google Maps
If an extension other than "html" is specified ("json" for example), and the view file "[controller]/[function].json" is not found, web2py looks for the view "generic.json". web2py comes with generic.html, generic.json, generic.jsonp, generic.xml, generic.rss, generic.ics (for Mac Mail Calendar), (for embedding Google Maps), and generic.pdf (based on fpdf). These generic views can be modified for each application individually, and additional views can be added easily.
Generic views are a development tool. In production every action should have its own view. In fact, by default, generic views are only enabled from localhost.
You can also specify a view with response.view = 'default/something.html'
Read more on this topic in Chapter 10.
If you go back to "EDIT" and click on index, you will now see the following HTML page:

Debugging toolbar

For debugging purposes you can insert
to the code in a view and it will show you some useful information, including the request, response and session objects, and list all db queries with their timing.

Let's count

Let's now add a counter to this page that will count how many times the same visitor displays the page.
web2py automatically and transparently tracks visitors using sessions and cookies. For each new visitor, it creates a session and assigns a unique "session_id". The session is a container for variables that are stored server-side. The unique id is sent to the browser via a cookie. When the visitor requests another page from the same application, the browser sends the cookie back, it is retrieved by web2py, and the corresponding session is restored.
To use the session, modify the default controller:
def index():
    if not session.counter:
        session.counter = 1
        session.counter += 1
    return dict(message="Hello from MyApp", counter=session.counter)
Notice that counter is not a web2py keyword but session is. We are asking web2py to check whether there is a counter variable in the session and, if not, to create one and set it to 1. If the counter is there, we ask web2py to increase the counter by 1. Finally we pass the value of the counter to the view.
A more compact way to code the same function is this:
def index():
    session.counter = (session.counter or 0) + 1
    return dict(message="Hello from MyApp", counter=session.counter)
Now modify the view to add a line that displays the value of the counter:



Number of visits: {{=counter}}

When you visit the index page again (and again) you should get the following HTML page:
The counter is associated with each visitor, and is incremented each time the visitor reloads the page. Different visitors see different counters.

Say my name

Now create two pages (first and second), where the first page creates a form, asks the visitor's name, and redirects to the second page, which greets the visitor by name.
yUML diagram
Write the corresponding actions in the default controller:
def first():
    return dict()

def second():
    return dict()
Then create a view "default/first.html" for the first action, and enter:
{{extend 'layout.html'}}

What is your name?

Finally, create a view "default/second.html" for the second action:
{{extend 'layout.html'}}

Hello {{=request.vars.visitor_name}}

In both views we have extended the basic "layout.html" view that comes with web2py. The layout view keeps the look and feel of the two pages consistent. The layout file can be edited and replaced easily, since it mainly contains HTML code.
If you now visit the first page, type your name:
and submit the form, you will receive a greeting:


The mechanism for form submission that we used before is very common, but it is not good programming practice. All input should be validated and, in the above example, the burden of validation would fall on the second action. Thus the action that performs the validation is different from the action that generated the form. This tends to cause redundancy in the code.
A better pattern for form submission is to submit forms to the same action that generated them, in our example the "first". The "first" action should receive the variables, process them, store them server-side, and redirect the visitor to the "second" page, which retrieves the variables. This mechanism is called a postback.
yUML diagram
Modify the default controller to implement self-submission:
def first():
    if request.vars.visitor_name:
        session.visitor_name = request.vars.visitor_name
    return dict()

def second():
    return dict()
Then modify the "default/first.html" view:
{{extend 'layout.html'}}
What is your name?
and the "default/second.html" view needs to retrieve the data from the session instead of from the request.vars:
{{extend 'layout.html'}}

Hello {{=session.visitor_name or "anonymous"}}

From the point of view of the visitor, the self-submission behaves exactly the same as the previous implementation. We have not added validation yet, but it is now clear that validation should be performed by the first action.
This approach is better also because the name of the visitor stays in the session, and can be accessed by all actions and views in the application without having to be passed around explicitly.
Note that if the "second" action is ever called before a visitor name is set, it will display "Hello anonymous" because session.visitor_name returns None. Alternatively we could have added the following code in the controller (inside the second function):
if not request.function=='first' and not session.visitor_name:
This is an ad hoc mechanism that you can use to enforce authorization on controllers, though see Chapter 9 for a more powerful method.
With web2py we can move one step further and ask web2py to generate the form for us, including validation. web2py provides helpers (FORM, INPUT, TEXTAREA, and SELECT/OPTION) with the same names as the equivalent HTML tags. They can be used to build forms either in the controller or in the view.
For example, here is one possible way to rewrite the first action:
def first():
    form = FORM(INPUT(_name='visitor_name', requires=IS_NOT_EMPTY()),
    if form.process().accepted:
        session.visitor_name = form.vars.visitor_name
    return dict(form=form)
where we are saying that the FORM tag contains two INPUT tags. The attributes of the input tags are specified by the named arguments starting with underscore. The requires argument is not a tag attribute (because it does not start by underscore) but it sets a validator for the value of visitor_name.
Here is yet another better way to create the same form:
def first():
    form = SQLFORM.factory(Field('visitor_name',
                                 label='what is your name?',
    if form.process().accepted:
        session.visitor_name = form.vars.visitor_name
    return dict(form=form)
The form object can be easily serialized in HTML by embedding it in the "default/first.html" view.
{{extend 'layout.html'}}
The form.process() method applies the validators and returns the form itself. The form.accepted variable is set to True if the form was processed and passed validation. If the self-submitted form passes validation, it stores the variables in the session and redirects as before. If the form does not pass validation, error messages are inserted into the form and shown to the user, as below:
In the next section we will show how forms can be generated automatically from a model.
In all our examples we have used the session to pass the user name from the first action to the second. We could have used a different mechanism and passed data as part of a redirect URL:
def first():
    form = SQLFORM.factory(Field('visitor_name', requires=IS_NOT_EMPTY()))
    if form.process().accepted:
        name = form.vars.visitor_name
    return dict(form=form)

def second():
    name = request.vars.visitor_name or redirect(URL('first'))
    return dict(name=name)
Mind that in general it is not a good idea to pass data from one action to another using the URL. It makes it harder to secure the application. It is safer to store the data in a session.


Your code is likely to include hardcoded strings such as "What is your name?". You should be able to customize strings without editing the code and in particular insert translations for these strings in different languages. In this way if a visitor has the language preference of the browser set to "Italian", web2py will use the Italian translation for the strings, if available. This feature of web2py is called "internationalization" and it is described in more detail in the next chapter.
Here we just observe that in order to use this feature you should markup strings that needs translation. This is done by wrapping a quoted string in code such as
"What is your name?"
with the T operator:
T("What is your name?")
You can also mark for translations strings hardcoded in views. For example

What is your name?


{{=T("What is your name?")}}

It is good practice to do this for every string in the code (field labels, flash messages, etc.) except for tables and field names.
Once the strings are identified and marked up, web2py takes care of almost everything else. The admin interface also provides a page where you can translate each string in the languages you desire to support.
web2py includes a powerful pluralization engine which is described in the next chapter. It is integrated with both the internationalization engine and the markmin renderer.

An image blog

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 named images and submit comments (posts).
As before, from the site page in admin, create a new application called images, 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, for lack of imagination, we call "". We assume the code below will replace any existing code in "". Models and controllers must have a .py extension since they are Python code. If the extension is not provided, it is appended by web2py. Views instead have a .html extension since they mainly contain HTML code.
Edit the "" file by clicking the corresponding "edit" button:
and enter the following:
db = DAL("sqlite://storage.sqlite")

   Field('title', unique=True),
   Field('file', 'upload'),
   format = '%(title)s')

   Field('image_id', 'reference image'),
   Field('body', 'text'))

db.image.title.requires = IS_NOT_IN_DB(db, db.image.title) = IS_IN_DB(db,, '%(title)s') = IS_NOT_EMPTY() = IS_EMAIL() = IS_NOT_EMPTY() = = False
Let's analyze this line by line.
Line 1 defines a global variable called db that represents the database connection. In this case it is a connection to a SQLite database stored in the file "applications/images/databases/storage.sqlite". When using SQLite, if the database file does not exist, it is created. You can change the name of the file, as well as the name of the global variable db, but it is convenient to give them the same name, to make it easy to remember.
Lines 3-6 define a table "image". define_table is a method of the db object. The first argument, "image", is the name of the table we are defining. The other arguments are the fields belonging to that table. This table has a field called "title", a field called "file", and a field called "id" that serves as the table primary key ("id" is not explicitly declared because all tables have an id field by default). The field "title" is a string, and the field "file" is of type "upload". "upload" is a special type of field used by the web2py Data Abstraction Layer (DAL) to store the names of uploaded files. web2py knows how to upload files (via streaming if they are large), rename them safely, and store them.
When a table is defined, web2py takes one of several possible actions:
  • if the table does not exist, the table is created;
  • if the table exists and does not correspond to the definition, the table is altered accordingly, and if a field has a different type, web2py tries to convert its contents;
  • if the table exists and corresponds to the definition, web2py does nothing.
This behavior is called "migration". In web2py migrations are automatic, but can be disabled for each table by passing migrate=False as the last argument of define_table.
Line 6 defines a format string for the table. It determines how a record should be represented as a string. Notice that the format argument can also be a function that takes a record and returns a string. For example:
format=lambda row: row.title
Lines 8-12 define another table called "post". A post has an "author", an "email" (we intend to store the email address of the author of the post), a "body" of type "text" (we intend to use it to store the actual comment posted by the author), and an "image_id" field of type reference that points to db.image via the "id" field.
In line 14, db.image.title represents the field "title" of table "image". The attribute requires allows you to set requirements/constraints that will be enforced by web2py forms. Here we require that the "title" is unique:
IS_NOT_IN_DB(db, db.image.title)Notice this is optional because it is set automatically given that Field('title', unique=True).
The objects representing these constraints are called validators. Multiple validators can be grouped in a list. Validators are executed in the order they appear. IS_NOT_IN_DB(a, b) is a special validator that checks that the value of a field b for a new record is not already in a.
Line 15 requires that the field "image_id" of table "post" is in As far as the database is concerned, we had already declared this when we defined the table "post". Now we are explicitly telling the model that this condition should be enforced by web2py, too, at the form processing level when a new comment is posted, so that invalid values do not propagate from input forms to the database. We also require that the "image_id" be represented by the "title", '%(title)s', of the corresponding record.
Line 20 indicates that the field "image_id" of table "post" should not be shown in forms, writable=False and not even in read-only forms, readable=False.
The meaning of the validators in lines 17-18 should be obvious.
Notice that the validator = IS_IN_DB(db,, '%(title)s')
can be omitted (and would be automatic) if we specify a format for referenced table:
db.define_table('image', ..., format='%(title)s')
where the format can be a string or a function that takes a record and returns a string.
Once a model is defined, if there are no errors, web2py creates an application administration interface to manage the database. You access it via the "database administration" link in the edit page or directly:
Here is a screenshot of the appadmin interface:
This interface is coded in the controller called "" and the corresponding view "appadmin.html". From now on, we will refer to this interface simply as appadmin. It allows the administrator to insert new database records, edit and delete existing records, browse tables, and perform database joins.
The first time appadmin is accessed, the model is executed and the tables are created. The web2py DAL translates Python code into SQL statements that are specific to the selected database back-end (SQLite in this example). You can see the generated SQL from the edit page by clicking on the "sql.log" link under "models". Notice that the link is not present until the tables have been created.
If you were to edit the model and access appadmin again, web2py would generate SQL to alter the existing tables. The generated SQL is logged into "sql.log".
Now go back to appadmin and try to insert a new image record:
web2py has translated the db.image.file "upload" field into an upload form for the file. When the form is submitted and an image file is uploaded, the file is renamed in a secure way that preserves the extension, it is saved with the new name under the application "uploads" folder, and the new name is stored in the db.image.file field. This process is designed to prevent directory traversal attacks.
Notice that each field type is rendered by a widget. Default widgets can be overridden.
When you click on a table name in appadmin, web2py performs a select of all records on the current table, identified by the DAL query > 0
and renders the result.
You can select a different set of records by editing the DAL query and pressing [Submit].
To edit or delete a single record, click on the record id number.
Because of the IS_IN_DB validator, the reference field "image_id" is rendered by a drop-down menu. The items in the drop-down are stored as keys (, but are represented by their db.image.title, as specified by the validator.
Validators are powerful objects that know how to represent fields, filter field values, generate errors, and format values extracted from the field.
The following figure shows what happens when you submit a form that does not pass validation:
The same forms that are automatically generated by appadmin can also be generated programmatically via the SQLFORM helper and embedded in user applications. These forms are CSS-friendly, and can be customized.
Every application has its own appadmin; therefore, appadmin itself can be modified without affecting other applications.
So far, the application knows how to store data, and we have seen how to access the database via appadmin. Access to appadmin is restricted to the administrator, and it is not intended as a production web interface for the application; hence the next part of this walk-through. Specifically we want to create:
  • An "index" page that lists all available images sorted by title and links to detail pages for the images.
  • A "show/[id]" page that shows the visitor the requested image and allows the visitor to view and post comments.
  • A "download/[name]" action to download uploaded images.
This is represented schematically here:
yUML diagram
Go back to the edit page and edit the "" controller, replacing its contents with the following:
def index():
    images = db().select(db.image.ALL, orderby=db.image.title)
    return dict(images=images)
This action returns a dictionary. The keys of the items in the dictionary are interpreted as variables passed to the view associated to the action. When developing, if there is no view, the action is rendered by the "generic.html" view that is provided with every web2py application.
The index action performs a select of all fields (db.image.ALL) from table image, ordered by db.image.title. The result of the select is a Rows object containing the records. Assign it to a local variable called images returned by the action to the view. images is iterable and its elements are the selected rows. For each row the columns can be accessed as dictionaries: images[0]['title'] or equivalently as images[0].title.
If you do not write a view, the dictionary is rendered by "views/generic.html" and a call to the index action would look like this:
You have not created a view for this action yet, so web2py renders the set of records in plain tabular form.
Proceed to create a view for the index action. Return to admin, edit "default/index.html" and replace its content with the following:
{{extend 'layout.html'}}

Current Images

    {{for image in images:}} {{=LI(A(image.title, _href=URL("show",}} {{pass}}
The first thing to notice is that a view is pure HTML with special {{...}} tags. The code embedded in {{...}} is pure Python code with one caveat: indentation is irrelevant. Blocks of code start with lines ending in colon (:) and end in lines beginning with the keyword pass. In some cases the end of a block is obvious from context and the use of pass is not required.
Lines 5-7 loop over the image rows and for each row image display:
LI(A(image.title, _href=URL('show',
This is a
  • ...
  • tag that contains an ... tag which contains the image.title. The value of the hypertext reference (href attribute) is:
    i.e., the URL within the same application and controller as the current request that calls the function called "show", passing a single argument to the function, LI, A, etc. are web2py helpers that map to the corresponding HTML tags. Their unnamed arguments are interpreted as objects to be serialized and inserted in the tag's innerHTML. Named arguments starting with an underscore (for example _href) are interpreted as tag attributes but without the underscore. For example _href is the href attribute, _class is the class attribute, etc.
    As an example, the following statement:
    {{=LI(A('something', _href=URL('show', args=123))}}
    is rendered as:
  • something
  • A handful of helpers (INPUT, TEXTAREA, OPTION and SELECT) also support some special named attributes not starting with underscore (value, and requires). They are important for building custom forms and will be discussed later.
    Go back to the edit page. It now indicates that " exposes index". By clicking on "index", you can visit the newly created page:
    which looks like:
    If you click on the image name link, you are directed to:
    and this results in an error, since you have not yet created an action called "show" in controller "".
    Let's edit the "" controller and replace its content with:
    def index():
        images = db().select(db.image.ALL, orderby=db.image.title)
        return dict(images=images)
    def show():
        image = db.image(request.args(0,cast=int)) or redirect(URL('index')) =
        form = SQLFORM(
        if form.process().accepted:
            response.flash = 'your comment is posted'
        comments = db(
        return dict(image=image, comments=comments, form=form)
    def download():
        return, db)
    The controller contains two actions: "show" and "download". The "show" action selects the image with the id parsed from the request args and all comments related to the image. "show" then passes everything to the view "default/show.html".
    The image id referenced by:
    in "default/index.html", can be accessed as:
    request.args(0,cast=int)from the "show" action. The cast=int argument is optional but very important. It attempts to cast the string value passed in the PATH_INFO into an int. On failure it raises a proper exception instead of causing a ticket. One can also specify a redirect in case of failure to cast:
    request.args(0,cast=int,otherwise=URL('error'))Moreover db.image(...) is a shortcut for
    The "download" action expects a filename in request.args(0), builds a path to the location where that file is supposed to be, and sends it back to the client. If the file is too large, it streams the file without incurring any memory overhead.
    Notice the following statements:
    • Line 7 creates an insert form SQLFORM for the table using only the specified fields.
    • Line 8 sets the value for the reference field, which is not part of the input form because it is not in the list of fields specified above.
    • Line 9 processes the submitted form (the submitted form variables are in request.vars) within the current session (the session is used to prevent double submissions, and to enforce navigation). If the submitted form variables are validated, the new comment is inserted in the table; otherwise the form is modified to include error messages (for example, if the author's email address is invalid). This is all done in line 9!.
    • Line 10 is only executed if the form is accepted, after the record is inserted into the database table. response.flash is a web2py variable that is displayed in the views and used to notify the visitor that something happened.
    • Line 11 selects all comments that reference the current image.
    The "download" action is already defined in the "" controller of the scaffolding application.
    The "download" action does not return a dictionary, so it does not need a view. The "show" action, though, should have a view, so return to admin and create a new view called "default/show.html".
    Edit this new file and replace its content with the following:
    {{extend 'layout.html'}}

    Image: {{=image.title}}

    {{if len(comments):}}


    {{for post in comments:}} {{}} says {{=post.body}}

    No comments posted yet


    Post a comment

    This view displays the image.file by calling the "download" action inside an tag. If there are comments, it loops over them and displays each one.
    Here is how everything will appear to a visitor.
    When a visitor submits a comment via this page, the comment is stored in the database and appended at the bottom of the page.

    Adding authentication

    The web2py API for Role-Based Access Control is quite sophisticated, but for now we will limit ourselves to restricting access to the show action to authenticated users, deferring a more detailed discussion to Chapter 9.
    To limit access to authenticated users, we need to complete three steps. In a model, for example "", we need to add:
    from import Auth
    auth = Auth(db)
    In our controller, we need to add one action:
    def user():
        return dict(form=auth())
    This is sufficient to enable login, register, logout, etc. pages. The default layout will also show options to the corresponding pages in the top right corner.
    We can now decorate the functions that we want to restrict, for example:
    def show():
    Any attempt to access[image_id]
    will require login. If the user is not logged it, the user will be redirected to
    The user function also exposes, among others, the following actions:
    Now, a first-time user needs to register in order to be able to log in and read or post comments.
    Both the auth object and the user function are already defined in the scaffolding application. The auth object is highly customizable and can deal with email verification, registration approvals, CAPTCHA, and alternate login methods via plugins.

    Adding grids

    We can improve this further using the SQLFORM.grid and SQLFORM.smartgrid gadgets to create a management interface for our application:
    def manage():
        grid = SQLFORM.smartgrid(db.image,linked_tables=['post'])
        return dict(grid=grid)
    with associated "views/default/manage.html"
    {{extend 'layout.html'}}

    Management Interface

    Using appadmin create a group "manager" and make some users members of the group. They will not be able to access
    and browse, search:
    create, update and delete images and their comments:

    Configuring the layout

    You can configure the default layout by editing "views/layout.html" but you can also configure it without editing the HTML. In fact, the "static/base.css" stylesheet is well documented and described in Chapter 5. You can change color, columns, size, borders and background without editing the HTML. If you want to edit the menu, the title or the subtitle, you can do so in any model file. The scaffolding app, sets default values of these parameters in the file "models/":
    response.title = request.application
    response.subtitle = 'customize me!' = 'you'
    response.meta.description = 'describe your app'
    response.meta.keywords = 'bla bla bla' = [ [ 'Index', False, URL('index') ] ]

    A simple wiki

    In this section, we build a simple wiki from scratch using only low level APIs (as opposed to using the built-in wiki capabilities of web2py demonstrated in the next section). 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 Markmin 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[xmlrpc] . The following diagram lists the actions that we need to implement and the links we intend to build among them.
    yUML diagram
    Start by creating a new scaffolding app, naming it "mywiki".
    The model must contain three tables: page, comment, and document. Both comment and document reference page because they belong to page. A document contains a file field of type upload as in the previous images application.
    Here is the complete model:
    db = DAL('sqlite://storage.sqlite')
    from import *
    auth = Auth(db)
    crud = Crud(db)
        Field('body', 'text'),
        Field('created_on', 'datetime',,
        Field('created_by', 'reference auth_user', default=auth.user_id),
        Field('page_id', 'reference page'),
        Field('body', 'text'),
        Field('created_on', 'datetime',,
        Field('created_by', 'reference auth_user', default=auth.user_id))
        Field('page_id', 'reference page'),
        Field('file', 'upload'),
        Field('created_on', 'datetime',,
        Field('created_by', 'reference auth_user', default=auth.user_id),
        format='%(name)s') = IS_NOT_IN_DB(db, 'page.title') = IS_NOT_EMPTY() = = False = = False = IS_NOT_EMPTY() = = False = = False = = False = IS_NOT_IN_DB(db, '')
    db.document.page_id.readable = db.document.page_id.writable = False
    db.document.created_by.readable = db.document.created_by.writable = False
    db.document.created_on.readable = db.document.created_on.writable = False
    Edit the controller "" and create the following actions:
    • index: list all wiki pages
    • create: add a new wiki page
    • show: show a wiki page and its comments, and add new comments
    • edit: edit an existing page
    • documents: manage the documents attached to a page
    • download: download a document (as in the images example)
    • search: display a search box and, via an Ajax callback, return all matching titles as the visitor types
    • callback: the Ajax callback function. It returns the HTML that gets embedded in the search page while the visitor types.
    Here is the "" controller:
    def index():
         """ this controller returns a dictionary rendered by the view
             it lists all wiki pages
         >>> index().has_key('pages')
         pages = db().select(,,
         return dict(pages=pages)
    def create():
         """creates a new empty wiki page"""
         form = SQLFORM('index'))
         return dict(form=form)
    def show():
         """shows a wiki page"""
         this_page =,cast=int)) or redirect(URL('index')) =
         form = SQLFORM( if auth.user else None
         pagecomments = db(
         return dict(page=this_page, comments=pagecomments, form=form)
    def edit():
         """edit an existing wiki page"""
         this_page =,cast=int)) or redirect(URL('index'))
         form = SQLFORM(, this_page).process(
             next = URL('show',args=request.args))
         return dict(form=form)
    def documents():
         """browser, edit all documents attached to a certain page"""
         page =,cast=int)) or redirect(URL('index'))
         db.document.page_id.default =
         db.document.page_id.writable = False
         grid = SQLFORM.grid(,args=[])
         return dict(page=page, grid=grid)
    def user():
         return dict(form=auth())
    def download():
         """allows downloading of documents"""
         return, db)
    def search():
         """an ajax wiki search page"""
         return dict(form=FORM(INPUT(_id='keyword',_name='keyword',
                  _onkeyup="ajax('callback', ['keyword'], 'target');")),
    def callback():
         """an ajax callback that returns a 
      of links to wiki pages""" query = pages = db(query).select( links = [A(p.title, _href=URL('show', for p in pages] return UL(*links)
    Lines 2-6 constitute a comment for the index action. Lines 4-5 inside the comment are interpreted by python as test code (doctest). Tests can be run via the admin interface. In this case the tests verify that the index action runs without errors.
    Lines 18, 27, and 35 try to fetch a page record with the id in request.args(0).
    Lines 13, 20 define and process create forms for a new page and a new comment and
    Line 28 defines and processes an update form for a wiki page.
    Line 38 creates a grid object that allows to view, add and update the comments linked to a page.
    Some magic happens in line 51. The onkeyup attribute of the INPUT tag "keyword" is set. Every time the visitor releases a key, the JavaScript code inside the onkeyup attribute is executed, client-side. Here is the JavaScript code:
    ajax('callback', ['keyword'], 'target');
    ajax is a JavaScript function defined in the file "web2py.js" which is included by the default "layout.html". It takes three parameters: the URL of the action that performs the synchronous callback, a list of the IDs of variables to be sent to the callback (["keyword"]), and the ID where the response has to be inserted ("target").
    As soon as you type something in the search box and release a key, the client calls the server and sends the content of the 'keyword' field, and, when the sever responds, the response is embedded in the page itself as the innerHTML of the 'target' tag.
    The 'target' tag is a DIV defined in line 52. It could have been defined in the view as well.
    Here is the code for the view "default/create.html":
    {{extend 'layout.html'}}

    Create new wiki page

    Assuming you are registered and logged in, if you visit the create page, you see the following:
    Here is the code for the view "default/index.html":
    {{extend 'layout.html'}}

    Available wiki pages

    [ {{=A('search', _href=URL('search'))}} ]
      {{for page in pages:}} {{=LI(A(page.title, _href=URL('show',}} {{pass}}
    [ {{=A('create page', _href=URL('create'))}} ]
    It generates the following page:
    Here is the code for the view "default/show.html":
    {{extend 'layout.html'}}


    [ {{=A('edit', _href=URL('edit', args=request.args))}} | {{=A('documents', _href=URL('documents', args=request.args))}} ] {{=MARKMIN(page.body)}}


    {{for post in comments:}} {{=db.auth_user[post.created_by].first_name}} on {{=post.created_on}} says {{=post.body}}

    Post a comment

    If you wish to use markdown syntax instead of markmin syntax:
    from gluon.contrib.markdown import WIKI as MARKDOWN
    and use MARKDOWN instead of the MARKMIN helper. Alternatively, you can choose to accept raw HTML instead of markmin syntax. In this case you would replace:
    (so that the XML does not get escaped, which web2py normally does by default for security reasons).
    This can be done better with:
    {{=XML(page.body, sanitize=True)}}
    By setting sanitize=True, you tell web2py to escape unsafe XML tags such as "
    Postar um comentário