One of the recent additions to web2py is the Create/Read/Update/Delete (CRUD) API on top of SQLFORM. CRUD creates an SQLFORM, but it simplifies the coding because it incorporates the creation of the form, the processing of the form, the notification, and the redirection, all in one single function. What that function is depends on what you want to do.
The first thing to notice is that CRUD differs from the other web2py APIs we have used so far because it is not already exposed. It must be imported. It also must be linked to a specific database. For example:
1 from gluon.tools import Crud
The first argument of the constructor is the current context globals() so that CRUD can access the local request, response, and session. The second argument is a database connection object, db.
The crud object defined above provides the following API:
• crud. tables () returns a list of tables defined in the database.
• crud .create (db. tablename) returns a create form for table tablename.
• crud. read(db. tablename, id) returns a readonly form for tablename and record id.
• crud.update (db. tablename, id) returns an update form for tablename and record id.
• crud.delete(db.tablename, id) deletes the record.
• crud.select(db.tablename, query) returns a list of records selected from the table.
• crud () returns one of the above based on the request.args(). For example, the following action:
1 def data: return dict(form=crud())
would expose the following URLs:
However, the following action:
1 def create_tablename:
2 return dict(form=crud.create(db.tablename))
would only expose the create method
While the following action:
1 def update_tablename:
2 return dict(form=crud.update(db.tablename, request.args(0)))
would only expose the update method
1 http://.../[app]/[controller]/update_tablename and so on.
The behavior of CRUD can be customized in two ways: by setting some attributes of the crud object or by passing extra parameters to each of its methods.
Was this article helpful?