O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Rapid Web Applications with TurboGears: Using Python to Create Ajax-Powered Sites

Book Description

“Dear PHP,

It’s over between us. You can keep the kitchen sink, but I want my MVC.

With TurboGears, I was able to shed the most heinous FileMaker Pro legacy ‘solu­tion’ imaginable. It has relationships based on fields that change frequently, causing ‘disappearing data.’ I replaced it with an easy to maintain TurboGears application. Defunkifying and normalizing many years worth of munged data took twice as long as developing the TurboGears’s application itself. TurboGears’s excellent set of tools and best-of-breed approach makes it so easy to build applications quickly.”

Isaac Csandl, Manager of Information Technology, Chicago Legal Search, Ltd.

“TurboGears has resulted in significant time savings for rPath. Before it was released, we ex­pected to spend significant time building a Web framework for our rPath Appliance Agent product. TurboGears sharpens our focus on building a quality application; it allows us to provide more value to our customers, rather than reinventing the Web wheel.”

Michael K. Johnson, rPath Founding Engineer and Coauthor of Linux Application Development, Second Edition

“I think this is the first time that a Web framework’s functionality has been so obvious.”

Bruce Eckel, Author of Thinking in Java and Thinking in C++

“TurboGears helped me build more complex Web applications more quickly and with fewer headaches than any other framework I’ve used. Just like Python itself, it made me more productive with a minimal learning curve.”

Quentin Hartman, System Administrator

“TurboGears has changed the way I develop Web applications, from model, to view, to controller. Thanks to the power of TurboGears, I was able to develop the first version of WhatWhat in less than a week of my spare time.”

Jonathan LaCour, Development Team Lead, Optio

“TurboGears has provided a way for me to greatly enhance my productivity by real­izing the potential of Web-based agile development with Python.”

Brandon Goldfedder, Vice President of Engineering, Information Extraction and Transport (IET Inc.), and Author of The Joy of Patterns

“TurboGears really changed the way I schedule project releases: It allows me to deliver them faster and with better quality than when I used to use GUI toolkits.”

Jorge Godoy, Owner of G2C Tech Consultoria in Brazil, former Lead Developer for Conectiva documentation team

“With TurboGears, I was able to transition my Python projects into Web applications as easily as possible.”

Benjamin T. Hamilton, Software Engineer

“Norwegian-based company Scanmine AS makes extensive use of Python and Turbo-Gears in all parts of its operation. TurboGears makes it a breeze to build highly sophis­ticated Web 2.0 applications with out-of-the-box features for multiple languages with full Unicode, REST, AJAX, RSS/Atom, and more. This enables Scanmine to put a face on their technology development in a minimal amount of time.

    “It has been said that there are as many Web frameworks as there are Python Web programmers. This apparent Web framework fragmentation has long been perceived as a weakness, until TurboGears came along and turned weakness into strength.”

Rune Hansen, Senior Systems Designer, Scanmine AS

“TurboGears is a well thought-out framework; the design choices it has made will help you be more productive. TurboGears will give you confidence with its foundation of stable best-of-breed Python components. If you are coming from other languages, consider working in TurboGears and Python to bring fun back into your Web develop­ment work.”

Jeff Marshall, Partner with FrozenBear

“When we started developing Oprius Foundations with TurboGears, we weren’t sure if it really would help us develop quicker and higher-quality code. After two months, we had a task manager to rival Tada List. After seven months, we had an entire contact management system to compete with the big boys.”

Jason Chu, Lead Developer, Oprius Software Inc.

“Conventional programming wisdom states that rewriting any working project from scratch is a bad idea. TurboGears was good enough to convince me to do this anyway, and I have been nothing but thrilled with the results. With TurboGears, I was able to implement an AJAX-based Web site with a nice Web API more easily than I ever thought possible. If you are trying to do either of those in Python, you owe it to your­self to look at this project. Using TurboGears was one of the few times in my program­ming career where a task was significantly less complicated than I thought possible.”

Adam Jones, Lead Programmer, RecursiveThought Software

Master TurboGears: The Easy Python Framework for Rapid Web Development

TurboGears harnesses the power of Python to provide a dynamic and easy-to-use Web development framework: one that
dramatically increases developer productivity, and makes it far easier to create dynamic, user-friendly, Ajax-enabled Web applications. Now, for the first time, there’s a definitive guide to TurboGears—coauthored by its creator, Kevin Dangoor.

This book will help experienced Web developers get productive with TurboGears—fast. You’ll quickly build your first TurboGears Web application—then extend it one step at a time, mastering the underlying libraries that make these enhancements possible. Next, the authors demonstrate TurboGears at work in a real-world application, by examining the code for “WhatWhat Status,” an open source project status tracking application. Finally, you’ll gain deep insight into the model, view, and controller technologies TurboGears is built upon: knowledge that will help you build far more robust and capable Python applications.

Coverage includes

  • Understanding the architecture of a TurboGears application

  • Mastering SQLObject, customizing it, and using it with TurboGears models

  • Utilizing TurboGears view technologies, including dynamic templates and MochiKit for Ajax

  • Bringing CSS, XHTML, and JavaScript together in reusable components with TurboGears Widgets

  • Using CherryPy and TurboGears controller technologies: from decorators to deployment

  • Exploring the TurboGears toolbox

  • Ensuring security and manag

Table of Contents

  1. Copyright
    1. Dedication
  2. Praise for Rapid Web Applications with TurboGears
  3. Prentice Hall Open Source Software Development Series
  4. Preface
  5. Acknowledgments
  6. TurboGears Fundamentals
    1. Introduction to TurboGears
      1. Why TurboGears?
        1. Making Easy Things Easy
        2. Making It Easy to Maintain
      2. The History of TurboGears
      3. TurboGears, Ajax, and Web 2.0
      4. Why TurboGears Values Being “Pythonic�
      5. What Can You Do with TurboGears?
      6. Coming Soon to a TurboGears Near You
      7. Summary
    2. Getting Started with TurboGears
      1. Installing TurboGears and SQLite
      2. Creating a Hello World Application
      3. Say Hi! (Simple Template)
      4. Custom Greetings (Hello from the Controller)
      5. Summary
    3. The Architecture of a TurboGears Application
      1. What Is MVC?
      2. Design Patterns and Object-Oriented MVC
      3. Understanding SQLObject and TurboGears Models
      4. Understanding CherryPy and TurboGears Controllers
      5. Understanding Kid and TurboGears Views
      6. MVC Meets Ajax
      7. Summary
  7. Building a Simple TurboGears Application
    1. Creating a Simple Application
      1. Building a Simple Bookmark Collection Site
      2. Testing TurboGears Applications
      3. A Simple Form to Add Bookmark
      4. Summary
    2. Enhancing Our Bookmark Application
      1. Updating Our Model
      2. Listing by Category
      3. Updating Our Form
      4. Tying Everything Together
      5. Selecting Categories
      6. Summary
  8. Exploring a Real World TurboGears Application
    1. Exploring More Complex Models in WhatWhat Status
      1. What Is WhatWhat Status?
      2. Logging in and Using WhatWhat Status
      3. Exploring the WhatWhat Status Model
      4. Writing Better Model Classes
        1. Keep All Model Logic in Model Methods
        2. Create New Classes to Encapsulate Complex Relational Logic
      5. Summary
    2. Controllers, Views, and JavaScript in the WhatWhat Status
      1. Dashboard Controller
        1. WhatWhat Security and Identity
        2. Exploring the Dashboard Index
      2. Dashboard Templates
      3. Adding a New Project
      4. Dashboard Controller new_project
      5. Summary
    3. RSS, Cookies, and Dynamic Views in WhatWhat Status
      1. Cookies and RecentChanges
      2. The Recent Changes Template
      3. WhatWhat Status Widgets
      4. Easy RSS with FeedController
      5. Summary
    4. Ajax and WhatWhat Status Projects
      1. Handling Ajax Requests
        1. Ajax Requests/HTML Responses
        2. Ajax Requests/JSON Responses
        3. Ajax and XML Responses
      2. Digging Into the Project Controller Methods
      3. A First Look at project.kid
        1. Laying the Groundwork for Our Project Page
        2. Using Ajax to Update Project Status and Descriptions
      4. Summary
  9. SQLObject and TurboGears Models
    1. SQLObject Basics
      1. ORM Basics
        1. Who Needs ORM?
        2. ORM Alternatives
        3. ORM Negatives
      2. Basic SQLObject Features
        1. Basic Connection Management
        2. Automatic DB Schema Creation from SQLObject-Derived Classes
        3. Fine Control on Behavior Using Metadata Class
        4. Automatic Table Description from Existing DB Schema
      3. Simple Database Queries
        1. Getting a Single Object by ID
        2. Getting an Entire Table
        3. Selecting Rows by Column Values
      4. Summary
    2. Mastering SQLObject
      1. Mapping Relationships
        1. One-to-Many Relationships (MultipleJoin)
        2. Many-to-Many Relationships (RelatedJoin)
      2. Straight SQL Queries
      3. Smart Queries
        1. sqlbuilder-Based Queries
        2. Selecting from Multiple Tables
        3. Joins
        4. Nested Queries
      4. Working with Large Result Sets
        1. Don’t list() a Large Result Set. Use Slices.
        2. Don’t Objectify a Large Result Set. Go with Straight SQL.
        3. Apply the Same Method to Bulk Inserts, Updates, or Deletes
        4. Don’t Go to the DB Multiple Times for the Same Objects
      5. Summary
    3. Customizing SQLObject Behavior
      1. Customizing SQLObject Classes with sqlmeta
        1. Inside the sqlmeta cless
        2. Columns, Indexes, and Joins
        3. Name Acrobatics
        4. Lazy Updates and Caching
        5. Expired Rows
        6. Default Order
      2. More-Advanced SQLObject Customization
        1. Adding Magic Attributes
        2. Overriding Attribute Access
      3. SQLObject and Inheritance
        1. Python Objects, Inheritance, and Composition
        2. Composition vs. Inheritance in Standard Python
        3. SQLObject Composition vs. Inheritance
      4. SQLObject and Transactions
        1. Transactions and Connections
        2. sqlhub and Transactions
        3. Encapsulating Transactions Using a Wrapper Function
        4. Encapsulating Transactions Using a Decorator
      5. Summary
  10. TurboGears View Technologies
    1. Dynamic Templates with Kid
      1. Creating Dynamic Templates with Kid
        1. Python-Powered Processing Directives
        2. Content-Producing Expressions
        3. Control Structures
        4. Kid’s Built-In Functions
      2. Beyond the Basics: Keeping Your Templates DRY (Don’t Repeat Yourself)
        1. Transformations Using py:match
        2. Creating Custom Tags with py:match
        3. Creating Parent Templates with py:extends
      3. Bringing It All Together
      4. Summary
    2. Creating Better JavaScript with MochiKit
      1. How to Use This Chapter
        1. MochiKit’s Packaging
        2. MochiKit’s Interactive Shell
      2. Introduction to MochiKit and Its Interactive Shell
      3. Base Functions
        1. The Comparison Problem
        2. More-Complicated Comparisons
        3. A Word about Objects in JavaScript
        4. JavaScript and Python: Not So Different After All
        5. Object Representation
        6. JSON Serialization
        7. Working with Arrays
        8. Pythonic Version of this
        9. Help with Calling Functions
        10. Dictionary-Like Objects
        11. Working with Query Strings
        12. Functions in MochiKit.Base
      4. Iterators in JavaScript
        1. Making an Iterator
        2. Functions from Itertools
        3. Functions Unique to MochiKit.Iter
      5. The Document Object Model
        1. Retrieving Elements
        2. Working with Style
        3. Creating DOM Nodes
        4. Simple Events
        5. Other DOM Functions
      6. Using MochiKit.Logging to Debug
        1. Using Logging
        2. Extended Logging
        3. Simple Logging Demo
      7. Working with Color
        1. The Demo
        2. More Ways to Get a Color
        3. Converting Colors
        4. Modifying Colors
      8. String Conversions and Value Formatting
        1. Working with Dates and Times
        2. Formatting Numbers
        3. Other String Formatting Functions
      9. Summary
    3. Effective Ajax with MochiKit
      1. Handling Asynchronous Events—Including Ajax Requests
        1. Dealing with Results That Arrive Later
        2. Making a Request
        3. Handling Errors
        4. Passing Parameters
        5. Limitations of Ajax
        6. Using JSON
        7. Working with Timers
        8. Canceling Deferreds
        9. Ajax, Timers, and Cancellation Combined
        10. More about Callbacks
      2. Handling JavaScript Events with MochiKit.Signal
        1. Getting Started with MochiKit.Signal
        2. Connecting and Disconnecting
        3. Using MochiKit’s Cross-Browser Event Objects
        4. Custom Events
      3. Visual Effects for That “Wow Factor�
        1. Rounded Corners
        2. Getting Started with Effects
        3. Effect Options
        4. The Core Effects
        5. Combination Effects
        6. Customizing Effect Behavior
        7. An Effects Demo
        8. Sortables and DragAndDrop
      4. Summary
    4. TurboGears Widgets: Bringing CSS, XHTML, and JavaScript Together in Reusable Components
      1. Understanding Widgets
        1. Instantiation Time Customizations
        2. Render Time Attribute Assignment
        3. Using Callables with Widgets
      2. Form Widgets
        1. Custom Form Layout
        2. Form Field Widgets
      3. Compound Widgets
      4. Widgets and Validation
        1. How FormEncode Validators Integrate into Form Widgets
        2. More Validators
        3. Basics of Schema Validation
      5. CSS, JavaScript, and Widgets
      6. Creating Custom Widgets
      7. Anatomy of an Ajax Widget
      8. Summary
  11. CherryPy and TurboGears Controller Technologies
    1. CherryPy and TurboGears Decorators
      1. CherryPy URL Parsing
      2. CherryPy and the HTTP Request/Response Cycle
      3. CherryPy Filters
        1. Input Filters
        2. Output Filters
        3. Creating Your Own Filters
      4. CherryPy and TurboGears Configuration
      5. Decorators
        1. expose()
        2. validate()
      6. Error and Exception Handling
        1. Validation Errors
        2. Multiple Handlers
        3. Exception Handling
      7. RESTful Resources in TurboGears
      8. Summary
    2. TurboGears Deployment
      1. Choosing Your Production Environment
        1. Operating System of the Server(s): Linux, Mac OS, Windows?
        2. Should I Run CherryPy behind Another Web Server?
        3. The Basics of Configuring TurboGears for Production
      2. Using mod_rewrite or mod_proxy to Connect to CherryPy
        1. Advantages/Drawbacks of Using a Proxy in front of CherryPy
        2. Configuring Apache with mod_rewrite
        3. Configuring Apache to Serve Static Content Directly
        4. Configuring CherryPy to Run Behind a Web Server
        5. Making Sure That CherryPy Stays Up
      3. Running CherryPy on mod_python
        1. Advantages/Drawbacks of Using mod_python
        2. Configuring Apache/CherryPy for mod_python
      4. Other Ways of Running CherryPy behind a Web Server
      5. Scalability of Your Site
        1. Scaling Sessions
        2. Scaling Your Application
        3. Scaling at a Lower Cost
      6. Summary
  12. TurboGears Extras
    1. The TurboGears Toolbox and Other Tools
      1. Toolbox Overview
      2. ModelDesigner
      3. CatWalk
      4. WebConsole
      5. Widget Browser
      6. Admi18n and System Info
      7. The tg-admin Command
      8. Other TurboGears Tools
      9. Summary
    2. Internationalization
      1. Dealing with Unicode in Python
      2. Dealing with Unicode in TurboGears
        1. SQLObject and Unicode
        2. Kid Templates
        3. Unicode in CherryPy’s Request/Response Cycle
      3. Translating Your Application
        1. Localization of Python Sources
        2. Localization of Kid Templates
        3. Auto-Detect User Language Preference
        4. Locale-Specific Objects
        5. Admin i18n Interface
        6. Toolbox admi18n Tool
        7. tg-admin i18n Command-line Tool
      4. Summary
    3. Testing a TurboGears Application
      1. Nose
      2. TurboGears testutil
      3. Mechanize
      4. Selenium
      5. Summary
    4. TurboGears Identity and Security
      1. Basic Authentication/Authorization with Identity
      2. Validating User Access with Identity
      3. Avoiding Common Security Pitfalls
      4. Summary
  13. Appendix
    1. SQLAlchemy
      1. A Quick Tour of SQLAlchemy
      2. SQLAlchemy in TurboGears
      3. Data Mapper and Active Record
      4. More about ActiveMapper
      5. How Objects Are Cached in SQLAlchemy
      6. Should I Use SQLAlchemy or SQLObject?
      7. Migrating a Project to SQLAlchemy
      8. Deployment Configuration
      9. Application Configuration
      10. Class Definitions
      11. Changing Calls to byName Methods
      12. Updating Queries
      13. Final Thoughts