Tải bản đầy đủ (.pdf) (459 trang)

Professional python frameworks web 2 0 programming with django and turbogears

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (10.31 MB, 459 trang )


Professional

Python® Frameworks
Web 2.0 Programming with Django®
and TurboGears™
Dana Moore
Raymond Budd
William Wright

Wiley Publishing, Inc.

ffirs.indd v

9/8/07 3:32:26 PM


ffirs.indd iv

9/8/07 3:32:26 PM


Professional

Python® Frameworks
Web 2.0 Programming with Django®
and TurboGears™
Acknowledgments ....................................................................................... xiii
Introduction ................................................................................................ xxi

Part I: Introduction to Python Frameworks


Chapter 1: Web 2.0, Python, and Frameworks ................................................. 3
Chapter 2: Web 2.0 with Traditional Python .................................................. 19
Chapter 3: Introducing the Frameworks ........................................................ 47

Part II: TurboGears
Chapter 4: Introduction to TurboGears ........................................................ 101
Chapter 5: User Identity and Visitor Tracking .............................................. 137
Chapter 6: Widgets ................................................................................... 169
Chapter 7: Advanced TurboGears Topics ..................................................... 203

Part III: Django
Chapter 8: Dblog: A Blog Implemented in Django ........................................ 241
Chapter 9: Django Views and Users............................................................ 275
Chapter 10: Advanced Django Topics: AJAX, RSS, and More ........................ 305

Part IV: Advanced Client-Side Topics
Chapter 11: MochiKit — Pythonic JavaScripting ......................................... 337
Chapter 12: Flash-Based Interfaces and TurboGears ................................... 359
Appendix A: Tools Used ............................................................................ 395
Index ........................................................................................................ 405

ffirs.indd i

9/8/07 3:32:24 PM


ffirs.indd ii

9/8/07 3:32:26 PM



Professional

Python® Frameworks
Web 2.0 Programming with
Django® and TurboGears™

ffirs.indd iii

9/8/07 3:32:26 PM


ffirs.indd iv

9/8/07 3:32:26 PM


Professional

Python® Frameworks
Web 2.0 Programming with Django®
and TurboGears™
Dana Moore
Raymond Budd
William Wright

Wiley Publishing, Inc.

ffirs.indd v


9/8/07 3:32:26 PM


Professional Python® Frameworks: Web 2.0 Programming
Django® and TurboGears™
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2007 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN-13: 978-0-470-13809-0
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
Library of Congress Cataloging-in-Publication Data
Moore, Dana, 1947Professional Python frameworks : Web 2.0 programming with Django and Turbogears / Dana Moore,
Raymond Budd, William Wright.
p. cm.
Includes index.
ISBN 978-0-470-13809-0 (pbk.)
1. Web site development. 2. Python (Computer program language) I. Budd, Raymond, 1976- II. Wright, William,
1964- III. Title.
TK5105.888.M663 2007
006.7'6—dc22
2007032138
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any
means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections
107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or
authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood

Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be
addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317)
572-3447, fax (317) 572-4355, or online at />Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties
with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties,
including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every
situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional
person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The
fact that an organization or Website is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Website
may provide or recommendations it may make. Further, readers should be aware that Internet Websites listed in
this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department within
the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress
are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and
other countries, and may not be used without written permission. Python is a registered trademark of Python Software Foundation. Django is a registered trademark of The World Company Corporation. TurboGears is a trademark of Kevin Dangoor. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is
not associated with any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be
available in electronic books.

ffirs.indd vi

9/8/07 3:32:27 PM


For Jane, who, in our 35 years of love, has encouraged in me the belief that I can reach for and attain higher goals
than I could ever imagine. And for my cherished daughter Caitlin, who is for me both luminous and a conductor of
light; both possessing genius and having the power to stimulate it in others.
—DM
For Leah. You continually amaze me with your thoughtfulness, unwavering support, and above all your remarkable
ability to make me laugh and smile. Also for my sisters, who have helped me out so many different times in so many

different ways.
—RB
For my two favorite girls, Karan and Annette. Your encouragement and inspiration make all things seem possible.
—WW

ffirs.indd vii

9/8/07 3:32:28 PM


ffirs.indd viii

9/8/07 3:32:28 PM


About the Authors
Dana Moore is a division scientist with BBN Technologies and is an acknowledged expert in the fields of
peer-to-peer and collaborative computing, software agent frameworks, and assistive environments. Prior
to joining BBN, Dana was chief scientist for Roku Technologies and a distinguished member of technical
staff at Bell Laboratories. Dana is a popular conference speaker and a university lecturer. He has written
articles for numerous computing publications and coauthored the books Peer-to-Peer: Building Secure,
Scalable, and Manageable Networks; Jabber Developer’s Handbook; and Rich Internet Applications. Dana holds a
Master of Science degree from the University of Maryland and a Bachelor of Science degree in industrial
design, also from the University of Maryland.
Raymond Budd is a software engineer with BBN Technologies. He has designed, developed, and supported a variety of web applications and other distributed systems in Java, Ruby, and Python. He has
been published in several conference proceedings such as the Eighteenth National Conference on Artificial
Intelligence and journals including Applied Intelligence. Additional areas of interest include knowledge
representations, knowledge engineering, and distributed planning and scheduling. He received a Bachelor of Science degree in computer science from the University of Pittsburgh.
William Wright is a senior principal investigator with SPARTA, where he develops networking software
for systems distributed across the globe. His interests include real-time embedded systems, software

architecture for reuse, and software agent frameworks. A frequent conference speaker, William has also
written for Dr. Dobb’s Journal, Java Developer’s Journal, and Embedded Systems Programming, among others.
He coauthored the books Jabber Developer’s Handbook and Beginning Java Networking. William holds a
Master of Science degree in computer science from George Mason University and a Bachelor of Music
degree in education from Indiana University.

ffirs.indd ix

9/8/07 3:32:28 PM


ffirs.indd x

9/8/07 3:32:29 PM


Credits

ffirs.indd xi

Acquisitions Editor

Vice President and Executive Group Publisher

Jenny Watson

Richard Swadley

Development Editor


Vice President and Executive Publisher

Maureen Spears

Joseph B. Wikert

Production Editor

Project Coordinator

Elizabeth Ginns Britten

Adrienne Martinez

Copy Editor

Proofreader

Kathryn Duggan

Candace English

Editorial Manager

Indexer

Mary Beth Wakefield

Jack Lewis


Production Manager

Anniversary Logo Design

Tim Tate

Richard Pacifico

9/8/07 3:32:29 PM


ffirs.indd xii

9/8/07 3:32:29 PM


Acknowledgments
The authors wish to thank the industry leaders who shared their thoughts with us in interviews. We
thank Kevin Dangoor, creator of TurboGears, for sharing his insights on the design and development of
Web 2.0 applications and the evolution of web application tools. We also appreciate the insights of
Adrian Holovaty, leader of the Django project, whose thoughts on high-level languages for web applications show where we’ve been and where we’re going.
We express our thanks to Edward Benson for his help managing the source code for this book. Thanks
also to Patrick Pinkowski for his assistance with the cover photo. We are especially grateful for the efforts
of Maureen Spears, our development editor at Wiley. Her combination of high standards and encouragement made the development of this book a joy.
Finally, and most importantly, we thank our friends, families, and significant others for their forbearance.
Writing is a solitary activity that tends to exclude others, even those most important to us, and we appreciate all their support and promise to somehow make up for the lost time and opportunities.

ffirs.indd xiii

9/8/07 3:32:29 PM



ffirs.indd xiv

9/8/07 3:32:29 PM


Contents
Acknowledgments
Introduction

xiii
xxi

Part I: Introduction to Python Frameworks
Chapter 1: Web 2.0, Python, and Frameworks
The Starting Line
What’s Web 2.0?
The History of Application Design for Content Creation (In One Easy Dose)

The Role of AJAX in Web 2.0
Leveraging the Power of DSLs
Leveraging the Power of TurboGears
Leveraging the Power of Django
Leveraging the Power of Python
Comparing the Frameworks
The Historical Perspective
Controller Invocation

Summary


Chapter 2: Web 2.0 with Traditional Python
Old-School Web Technologies

4
4
4

10
10
11
12
12
13
13
14

17

19
19

XML
HTML
HTTP
SQL
JavaScript
CGI and Python

19

21
23
24
25
25

A Simple Example

25

Architecture
The HTML Page
The JavaScript Code
The Database
The Python CGI Program

Summary

ftoc.indd xv

3

29
30
33
38
42

45


9/10/07 11:33:01 AM


Contents
Chapter 3: Introducing the Frameworks
Web Application Frameworks
MVC in Web Application Frameworks
Common Web Application Framework Capabilities

Introduction to TurboGears
TurboGears History
Main TurboGears Components
Alternate Components
MVC Architecture in TurboGears
Creating an Example Application
The Controller and View

Introduction to Django
Django History
Main Django Components
Alternate Components
MVC Architecture in Django
Creating an Example Application

Summary

47
48
48
50


52
52
52
53
53
54
61

71
71
71
72
72
73

92

Part II: TurboGears
Chapter 4: Introduction to TurboGears
TurboGears Components
TurboGears
TurboGears
TurboGears
TurboGears

Models (SQLObjects)
Controllers
Views (Kid Templates and MochiKit)
Widgets


An Example: A Simple Blog Site
Creating the Project
Defining the Model
Using TGCrud
Creating the Blog Author Views with TGCrud
Creating the Blog Entry Views with TGCrud
Replacing the Blog Welcome Page
Changing Your Site’s Look and Feel

Summary

Chapter 5: User Identity and Visitor Tracking
Tracking Visits through Cookies
Managing User Identity

101
101
101
102
103
104

104
105
105
108
110
118
128

131

136

137
138
140

xvi

ftoc.indd xvi

9/10/07 11:33:03 AM


Contents
User Identity Model Objects
Identity Configuration Options
Other Identity Framework Components
Using the Identity Model Objects
Using the Identity Module

Visitor Tracking
Visitor Tracking Model Objects
Visitor Tracking Configuration Options
Visitor Tracking Plug-Ins
Adding Visitor Tracking

Summary


Chapter 6: Widgets

140
143
144
144
150

159
160
161
162
162

168

169

TurboGears Widgets
Using the Widget Browser
Using Existing Widgets

170
172
173

Defining the Model Object
Accepting User Comments

173

174

Creating New Widgets
Creating a Simple Hello Widget
Creating a Comment Widget

Summary

Chapter 7: Advanced TurboGears Topics
Your Assignment
The Operational Concept
Designing the Model
TurboGears Toolbox
The Model
The Controller

The View
Adding RSS Feed Capability
Summary

185
185
189

201

203
204
205
206

206
210
216

227
234
237

Part III: Django
Chapter 8: Dblog: A Blog Implemented in Django
Django Design Philosophies
An Example: A Simple Blog Site

241
241
242

xvii

ftoc.indd xvii

9/10/07 11:33:03 AM


Contents
Initializing the Project
Initializing the Application
Creating the Model
Exploring the Model with Django’s Admin Interface
Creating the Views


Summary

Chapter 9: Django Views and Users
Template Inheritance
The DRY Problem
Defining a Base Template
Using the {% extends %} Directive

Generic Views
List-Detail Generic Views
Other Generic Views

User Authentication and Authorization
Installing User Management
The User Model
Authenticating a User
Enhancing the Base Template
User Permissions
Creating a User

Summary

Chapter 10: Advanced Django Topics: AJAX, RSS, and More
AJAX and Django
MochiKit
Django Serialization for AJAX
AJAX-ified Blog Example

Django Add-Ons

django.contrib Add-Ons
Other Add-Ons
RSS in Detail

Deploying Django with Apache HTTPD
Installing and Configuring Apache
Configuring Other Items

Summary

242
245
246
251
255

273

275
276
276
277
279

282
282
284

285
285

286
287
290
293
297

303

305
306
306
307
311

320
320
321
321

327
327
328

329

xviii

ftoc.indd xviii

9/10/07 11:33:03 AM



Contents
Part IV: Advanced Client-Side Topics
Chapter 11: MochiKit — Pythonic JavaScripting
Why MochiKit?
What Is MochiKit?
What’s Inside MochiKit?
MochiKit.Async
MochiKit.Base
MochiKit.DOM
MochiKit.Logging
MochiKit.Signal
MochiKit.Visual
MochiKit Miscellany

Summary

Chapter 12: Flash-Based Interfaces and TurboGears
The Flex Difference
What’s Flex and Why Should I Use It?

A Flex2-based Blog
The Supporting Model
The Application Controller
The Flex Front-End
FBlog’s MXML Implementation
Deconstructing FBlog

Summary


337
338
341
341
342
349
351
352
352
355
357

357

359
359
360

380
381
382
384
385
387

392

Appendix A: Tools Used


395

Index

405

xix

ftoc.indd xix

9/10/07 11:33:04 AM


ftoc.indd xx

9/10/07 11:33:04 AM


Introduction
We Python developers have always been a proud lot, able to create desktop solutions with a variety of
user experience libraries, ranging from GTK to PythonCard to WxPython. We Pythonists have always
prided ourselves in being the best example of an end-to-end, batteries-included delivery system that
could create anything imaginable for the desktop user. Even in the early days of the Web, Pythonistas
led the way with Zope, and later Twisted.
Imagine the surprise of many of us when Ruby on Rails appeared suddenly and seemed to suck all the
air out of the room when the topic of Web 2.0 frameworks was discussed. Python’s rarely challenged
position of agile-language king of the desktop hardly mattered anymore.
Most Python developers had become accustomed to having a common set of rich client APIs for Windows, MAC OS X, and Linux. Thus, many Pythonists, although familiar with the Rich Client Platform
(RCP) model, were suddenly in the uncomfortable and unfamiliar position of having fallen behind in the
emerging Web 2.0 world.

Now this status quo has changed, and there are two strong end-to-end frameworks (Django and TurboGears) available for the Python Web 2.0 developer. Even if you haven’t had exposure to the buzzwords
or development model for Web 2.0 applications, this book will help you along that path. AJAX (Asynchronous JavaScript and XML), for example, is a hugely important element of the Web 2.0 interaction
model, and it is well covered and explained in examining both Django and TurboGears.
In addition, there’s now growing recognition, even in the most stolid of enterprises, of an important shift in
customer demand that promises to change the very foundations of how we develop and deploy applications. Customers are now specifying Web 2.0 capabilities in new applications development and even in retrofitting current applications to this new model, and the Web itself is undergoing a shift from a collection of
news articles, static forms, and bulletin boards to a virtual application-hosting platform in and of itself.
This book is right at the front of this trend for Python developers. Together, we will explore the elements
of this change in browser-based applications—from greater dynamism and responsiveness to faster development cycles to greater embrace of social networking. In this book, the objective is to prepare both
the corporate and the independent developer to take advantage of this new emerging landscape. As the
world of shrink-wrapped boxes of client-side software begins to wane, a new ecology of Rich Internet
Applications (RIAs) is emerging to bring both developers and end users new benefits that take full advantage of today’s connected world. Python developers who can reap the benefits of this new ecology
will prosper and stay at the front of their professional ranks.

Who Is This Book For?
This book is for people who are (or want to be) professional web application developers. In this book,
you’ll see how to take advantage of the latest technology to create compelling web applications, and create them fast. All of the techniques and technologies you’ll see in this book are designed to help you get a
professional website up quickly, without creating an unmaintainable pile of spaghetti code.

flast.indd xxi

9/7/07 11:37:54 AM


Introduction
We do assume that you know at least a little Python. If you’re not already on the Python bandwagon, maybe
the tools and techniques in this book can convince you to hop on. Python is a very readable language and
there are tons of good tutorials and references in print and on the Web to help you get up to speed.

What Is This Book’s Focus?
Like our readers, the authors are all professional corporate software developers who use agile languages

such as Python and Ruby with Web 2.0 techniques to deliver network-based applications to real customers, both commercial and government. We know that the quickest road to understanding code and APIs
is to review working code examples, but often books consist of a stream of simple didactic examples. Although this approach may reveal important points of a topic, it ultimately leaves you unfulfilled because
the examples don’t build anything more compelling outside the context of the point the author is trying
to make. This book builds an interesting and feature-complete application in each of three paradigms
(Django, TurboGears, and Flash/Flex2-fronting TurboGears) as a unifying theme holding the book
together and to give you points of comparison for multiple Python-based solutions to the same problem.

Leveraging the Rest of the Book: The Roadmap
As mentioned back at the beginning of this introduction, this book was written by and for developers. We
developers (you included) are a simple tribe. Give us some fun examples to work with and we’ll figure out
everything we need for working through them. So that’s the goal for the book—to cover the important topics
in Web 2.0 and show you how to achieve results using a combination of Python and modern frameworks.

Part I: Introduction to Python Frameworks
In Chapter 1, “Web 2.0, Python, and Frameworks,” you’ll have a whirlwind history lesson about application development from the desktop to the Web 2.0 era. You’ll see how the need for web frameworks
evolved and how some of the early responses (think J2EE) failed for most developers. You’ll have a brief
introduction to the set of tools used later in the book, including AJAX, domain-specific languages (DSLs),
Python, TurboGears, Django, JavaScript, and so on. At the end of this chapter, you’ll understand how
they are not just the new thing, but a fundamentally different and better thing.
In Chapter 2, “Web 2.0 with Traditional Python,” you’ll see an example of Web 2.0 created without using
any frameworks at all. That will help to reinforce the notion that you can use normal Python libraries to
write perfectly good Web 2.0 applications. This chapter offers a tutorial web application that demonstrates this point. All the hallmark features of a modern Web 2.0 application, including AJAX interaction
and XMLHttpRequest (XHR) handling using a combination of Python CGI scripting on the server and
JavaScript on the browser, will be shown. From the example application, you’ll be able to understand
that the skills you already have can produce Web 2.0 applications that are as compelling as those produced by advanced frameworks.
However, after you finish Chapter 3, “Introducing the Frameworks,” chances are good you will never want to
return to writing modern RIAs the painful old-school way. You’ll be introduced to an easier way to combine
Python with frameworks to write Web 2.0 applications, and get initial exposure to both frameworks covered
by the book. After this chapter, you will have a much greater appreciation of why frameworks are important,
why they are likely to save major time and frustration in the development cycle, and what characterizes a

framework. The differences in creating an application using only the techniques explained in Chapter 2 versus using the frameworks approach should be much clearer by the end of this chapter. The chapter ends with

xxii

flast.indd xxii

9/7/07 11:37:55 AM


×