TurboGears2 tutorial to create a simple MVC application

In this post lets talk about, making a simple note taking application using TurboGears. The post assumes that you know what MVC means, and expects familiarity with python and virtual environment. We are about to design a simple note taking application,which provides the users the features to create, edit and delete notes.

Overview:

TurboGears is another Python Web Framework designed around the MVC architecture, consisting of several WSGI components. It was created in 2005 by Kevin Dangoor. TurboGears is built around the following libraries:

  1. SQLAlchemy for the ORM.
  2. Genshi as the template engine.
  3. Pylons as the controller.
  4. Paster as the default webserver.
  5. Repoze which brings in the goodness of Zope, to handle authentication and authorization.
  6. ToscaWidgets to create forms and complex GUIs.

Installation:

Create a new virtual environment, and install the requirements from here.

Creating the Project:

(tg2envi)$ paster quickstart TgDemo Enter package name [tgdemo]: tg2notes Would you prefer mako templates? (yes/[no]): no Do you need authentication and authorization in this project? ([yes]/no): no ...... (tg2envi)$ cd TgDemo (tg2envi)$ python setup.py develop (tg2envi)$ paster setup-app development.ini (tg2envi)$ paster serve development.ini

The above command starts a server at port 8080. Once everything goes fine, you will see a directory structure as follows:

|-- config |-- controllers |-- i18n | '-- ru | '-- LC_MESSAGES |-- lib |-- model |-- public | |-- css | |-- images | '-- javascript |-- templates |-- tests | |-- functional | '-- models '-- websetup

Our major concern is writing database models and controllers to serve and operate on the data we have in our database.

Overview of MVC with TurboGears

Models:

The above directory structure shows a folder, model, you create a file file_name.py and write your class. We will get deeper in a short while.

Controllers and Templates:

From the folder structure visible above, there is a folder controllers, which contains a file root.py. This file is responsible for mapping urls to html templates applying some business logic to it. A small example to illustrate this:

 from tgnotes.model import DBSession, metadata, Note
 class RootController(BaseController):

      error = ErrorController()

      @expose("tgnotes.templates.note_list")
      def list(self):
       """List all notes in the database"""
            return dict(notes=DBSession.query(Note),
                             page='Note list')

Along with other imports, we import our database from the model. The RootController derives from the BaseController class. The url name is the name of the function, meaning: the above function will serve to the url /list. The @expose decorator tells which template to pick for the current url. A list of decorators can be found here. We pass a queryset, which will be rendered in the template.

We can go on writing functions to handle each of the edit, delete and create operations, but turbogears provides a CrudRestController class and we will leverage the feature to build our application. With the above background lets plunge into creating the application.

Database model design:

The database we need for our app, contains the following:

  • note title
  • note description
  • note author
  • subject to which the notes belong
  • date

To achieve the above purpose, we create a file called note.py in the model directory. The code can be found here.

Writing Controllers

Lets talk a little about the functionality in detail. When the user comes in, we want to show him a list of all the notes. The user is then given a choice to edit or delete each of the note, or to create a new note. For the purpose of creating and editing forms we need two forms note_add_form and note_edit_form.

Form Design

A good practice is to create a folder called widgets parallel to the controllers folder. We create a file called forms.py. We use sprox for schema based widget generation. Something analogous to django model forms. This will help us to pre-populate the form fields with the existent data while rendering edit forms. The code can be found here. All we need to do now is to import these forms in the root controller and they will render.

The code for root.py can be found here. Lets peep a little into the code. We first create a NoteController which inherits from the CrudRestController, all the options are listed here. We pass this to RootController. We specify that the NoteTable should not display the note_id. This is all we need to do, if your server is running and you have followed along all the steps, you will have a functional notes application. I will be happy to look into any of your doubt/suggestion/clarification.

Mentioned below is a summary of the steps we carried out:

Comments

blog comments powered by Disqus