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 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, for lack of imagination, we call "db.py". 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 "db.py" file by clicking the corresponding "edit" button:

Define Table Pic

and enter the following:

7 db.define_table( 'comment',

13 db.image.title.requires = [IS_NOT_EMPTY(),

16 db.comment.image_id.requires = IS_IN_DB(db, db.image.id, 'i(title)s')

17 db.comment.author.requires = IS_NOT_EMPTY ()

18 db.comment.email.requires = IS_EMAIL()

19 db.comment.body.requires = IS_NOT_EMPTY ( )

21 db.comment.image_id.writable = db.comment.image_id.readable = 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.db". In the SQLite case, if the database 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-5 define a table "image", define.tabie 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: a) if the table does not exist, the table is created; b) 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; c) 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=Faise as the last argument of define.tabie.

• Lines 7-11 define another table called "comment". A comment has an "author", an "email" (we intend to store the email address of the author of the comment), 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 lines 13-14 db.image.titie 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 not empty (is_not_empty ()) and that it is unique (is_not_in_db (db, db.image.title )). 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 16 requires that the field "image_id" of table "comment" is in db. image . id. As far as the database is concerned, we had already declared this when we defined the table "comment". 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 18 indicates that the field "image_id" of table "comment" should not be shown in forms, writable=False and not even in readonly forms, readable=False.

The meaning of the validators in lines 17-19 should be obvious.

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:

1 http://127.0.0.1:8000/images/appadmin

Here is a screenshot of the appadmin interface:

This interface is coded in the controller called "appadmin.py" 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 databasejoins.

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.

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

and renders the result.

You can select a different set of records by editing the SQL query and pressing "apply".

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 (db. image .id), but are represented by their db.image.titie, 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:

Go back to the [EDIT] page and edit the "default.py" controller, replacing its contents with the following:

2 images = db().select(db.image.ALL, orderby=db.image.title)

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

2 <h1>Current Images</h1>

5 {{= LI(A(image.title, _href=URL(r=request, f="show", args = image.id)))

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:

1 LI(A(image.title, _href=URL(r=request, f= 'show', args=image.id))

This is a <li>.. .</li> tag that contains an <a href=" ...">.. .</a> 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 r=request, calling the function called "show" and passing a single argument to the function, args = image. id.

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:

1 {{=LI(A('something', _href=URL(r=request, f='show', args=123))}}

is rendered as:

1 <li><a href="/images/default/show/123">something</a></li>

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 "default.py exposes index". By clicking on "index", you can visit the newly created page:

1 http://127.0.0.1:8000/images/default/index

which looks like:

If you click on the image name link, you are directed to:

1 http://127.0.0.1:8000/images/default/show/l

and this results in an error, since you have not yet created an action called "show" in controller "default.py".

Let's edit the "default.py" controller and replace its content with:

2 images = db().select(db.image.ALL, orderby=db.image.title)

3 return dict(images=images)

6 image = db(db.image.id==request.args(0)).select()[0]

7 form = SQLFORM(db.comment)

8 form.vars.image_id = image.id

9 if form.accepts(request.vars, session):

10 response .flash = 'your comment is posted'

11 comments = db(db.comment.image_id= = image.id).select()

12 return dict(image=image, comments=comments, form=form)

15 return response .download(request, 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 ) from the "show" action.

The "download" action expects a filename ) , 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 db. comment 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 db.comment 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. web2py vari able 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 "default.py" 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" by typing "default/show" in the create view form:

«no design images

http://127.0,0. l:8000/admin/default/de

design images http://127.0,0. l:8000/admin/default/de

Edit application "images'

[ models | controllers [ views | languages | static \ modules ]

Models

Controllers

Views the presentations layer, views are also known as templates

• appadmin.html [ edit | html edit [ delete ] extends layout.html

• default/index.html [edit [ htmledit | delete] extends Iayout.htmI

• default/user .html [edit | htmledit | delete ] extends layout.html

• generic.html [ edit | htmledit | delete ] extends layout.html

• layout.html [ edit | htmledit | delete ] includes webapy_ajax.html

Edit this new file and replace its content with the following:

4 <img width= "200px"

5 src= "{{=URL(r=request, f='download', args=image.file)}}" />

8 <h2>Comments</h2><br /><p>

9 {{for comment in comments:}}

10 <p>{{=comment.author}} says <i>{{=comment.body}}</i></p>

13 <h2>No comments posted yet</h2>

This view displays the image.file by calling the "download" action inside an <img ... /> tag. If there are comments, it loops over them and displays each one.

y submit ^

Languages Static files Modules

Powered by web2py (TM) created by Massimo Di Pierre © 2007, 2008,2009

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.

Was this article helpful?

0 0
Creating The Prefect YouTube Marketing Video

Creating The Prefect YouTube Marketing Video

Create the Perfect You Tube Marketing Video-5 Tips To Get it Right. You can use You Tube to market your business, product, or services. However, you need a good video in order to draw traffic and make people want to visit your website after they have finished watching.

Get My Free Ebook


Responses

  • juliane
    How to access image web2py from table?
    9 years ago
  • dennis
    Can web2py be used to store large data?
    9 years ago
  • alberic noakes
    How to upload picture in large number in web2py?
    9 years ago

Post a comment