www.it-ebooks.info
Python 3 Web Development
Beginner's Guide
Use Python to create, theme, and deploy unique web
applicaons
Michel Anders
BIRMINGHAM - MUMBAI
www.it-ebooks.info
Python 3 Web Development
Beginner's Guide
Copyright © 2011 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system,
or transmied in any form or by any means, without the prior wrien permission of the
publisher, except in the case of brief quotaons embedded in crical arcles or reviews.
Every eort has been made in the preparaon of this book to ensure the accuracy of the
informaon presented. However, the informaon contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.
Packt Publishing has endeavored to provide trademark informaon about all of the
companies and products menoned in this book by the appropriate use of capitals. However,
Packt Publishing cannot guarantee the accuracy of this informaon.
First published: May 2011
Producon Reference: 1060511
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-849513-74-6
www.packtpub.com
Cover Image by Rakesh Shejwal ([email protected])
Cover Work
Kruthika Bangera
www.it-ebooks.info
About the Author
Michel Anders, aer his chemistry and physics studies where he spent more me on
computer simulaons than on real world experiments, the author found his real interests
lay with IT and Internet technology, and worked as an IT manager for several dierent
companies, including an Internet provider, a hospital, and a soware development company.
Aer his inial exposure to Python as the built-in scripng language of Blender, the popular
3D modeling and rendering suite, the language became his tool of choice for many projects.
He lives happily in a small converted farm, with his partner, three cats, and twelve goats.
This tranquil environment proved to be ideally suited to wring his rst book, Blender 2.49
Scripng (Packt Publishing, 978-1-849510-40-0).
He loves to help people with Blender and Python-related quesons and may be contacted as
'varkenvarken' at
http://www.blenderartists.org/ and maintains a blog on Python-
specic subjects at http://michelanders.blogspot.com/.
For Clemenne, always.
www.it-ebooks.info
About the Reviewers
Michael Driscoll has been programming Python since the Spring of 2006 and has
dabbled in other languages since the late ninees. He graduated from the University with
a Bachelors of Science degree, majoring in Management Informaon Systems. Michael
enjoys programming for fun and prot. His hobbies include Biblical apologecs, blogging
about Python at http://www.blog.pythonlibrary.org/, and learning photography.
Michael currently works for the local government, where he does programming with Python
as much as possible. Michael was also a Technical Reviewer for Python 3: Object Oriented
Programming by Dusty Phillips and Python Graphics Cookbook by Mike Ohlson de Fine (both
by Packt Publishing).
I would like to thank my friends and family for their support and the fun
people/
.
www.it-ebooks.info
www.PacktPub.com
Support les, eBooks, discount offers, and more
You might want to visit www.PacktPub.com for support les and downloads related to your
book.
Did you know that Packt oers eBook versions of every book published, with PDF and ePub
les available? You can upgrade to the eBook version at
www.PacktPub.com and as a print
book customer, you are entled to a discount on the eBook copy. Get in touch with us at
[email protected] for more details.
At
www.PacktPub.com, you can also read a collecon of free technical arcles, sign up for a
range of free newsleers, and receive exclusive discounts and oers on Packt books and eBooks.
http://PacktLib.PacktPub.com
Do you need instant soluons to your IT quesons? PacktLib is Packt's online digital book
library. Here, you can access, read and search across Packt's enre library of books.
Why Subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view nine enrely free books. Simply use your login credenals for
immediate access.
www.it-ebooks.info
www.it-ebooks.info
Table of Contents
Preface 1
www.it-ebooks.info
Table of Contents
[ ii ]
Chapter 2: Creang a Simple Spreadsheet 29
Python 3 30
Time for acon – installing Python 3 CherryPy 30
Time for acon – installing CherryPy 31
Installing jQuery and jQuery UI 31
Serving an applicaon 32
Time for acon – serving a dummy applicaon 33
Time for acon – serving HTML as dynamic content 34
Who serves what: an overview 36
HTML: separang form and content 37
Time for acon – a unit convertor 38
HTML: form-based interacon 39
JavaScript: using jQuery UI widgets 40
Time for acon – conversion using unitconverter.js 40
jQuery selectors 42
CSS: applying a jQuery UI theme to other elements 43
Time for acon – converng a unit convertor into a plugin 45
JavaScript: creang a jQuery UI plugin 46
Designing a spreadsheet applicaon 51
Time for acon – serving a spreadsheet applicaon 51
HTML: keeping it simple 52
JavaScript: creang a spreadsheet plugin 52
The missing parts 58
Summary 58
Chapter 3: Tasklist I: Persistence 59
Designing a tasklist applicaon 59
Time for acon – creang a logon screen 62
TaskDB – interfacing with the database 106
Time for acon – connecng to the database 106
Time for acon – storing and retrieving informaon 107
Time for acon – updang and deleng informaon 109
Tesng 111
Time for acon – tesng factorial.py 112
Now what have we gained? 113
Time for acon – wring unit tests for tasklistdb.py 114
Designing for AJAX 116
Click handlers 120
The applicaon 121
Time for acon – pung it all together 123
Have a go hero – refreshing the itemlist on a regular basis 125
Summary 126
Chapter 5: Enes and Relaons 127
Designing a book database 127
The Enty class 128
Time for acon – using the Enty class 129
Time for acon – creang instances 132
The Relaon class 138
Time for acon – using the Relaon class 138
Relaon instances 141
Time for acon – dening the Books database 144
The delivery layer 150
Time for acon – designing the delivery layer 151
Time for acon – adding a new book 162
www.it-ebooks.info
Table of Contents
[ iv ]
Auto compleon 165
Time for acon – dening new relaons: how it should look 217
Implemenng the MetaRelaon and AbstractRelaon classes 219
Adding new methods to exisng classes 222
Browsing lists of enes 224
Time for acon – using a table-based Enty browser 224
Time for acon – examining the HTML markup 229
Caching 232
The books applicaon revisited 236
Time for acon – creang a books applicaon, take two 236
Summary 242
www.it-ebooks.info
Table of Contents
[ v ]
Chapter 8: Managing Customer Relaons 243
A crical review 243
Designing a Customer Relaonship Management applicaon 244
Time for acon – implemenng a basic CRM 244
Adding and eding values 248
Time for acon – adding an instance 249
Time for acon – eding an instance 251
Adding relaons 257
Picklists 259
Time for acon – implemenng picklists 259
Summary 262
Chapter 9: Creang Full-Fledged Webapps: Implemenng Instances 263
Even more relaons 263
Time for acon – showing one-to-many relaonships 264
Time for acon – adapng MetaRelaon 266
Time for acon – enhancing Display 270
Time for acon – enhancing Browse 271
Python 3 Web Development Beginner's Guide shows you how to independently build your
own web applicaon that is easy to use, performs smoothly, and is themed to your taste—all
without having to learn another web framework.
Web development can take me and is oen ddly to get right. This book will show you
how to design and implement a complex program from start to nish. Each chapter looks
at a dierent type of web applicaon, meaning that you will learn about a wide variety
of features and how to add them to your customized web applicaon. You will also learn
to implement jQuery into your web applicaon to give it extra funconality. By using the
right combinaon of a wide range of tools, you can have a fully funconal, complex web
applicaon up and running in no me.
A praccal guide to building and customizing your own Python web applicaon, without the
restricon of a pre-dened framework.
What this book covers
Chapter 1, Choosing Your Tools, looks at the many aspects of designing web applicaons.
The idea is to provide you with an overview that may help you recognize components in
subsequent chapters and give you some insight into the arguments used to decide which
tool or library to use. We also illustrate some issues that are relevant when designing an
applicaon that does not deal with coding directly, such as security or usability.
Chapter 2, Creang a Simple Spreadsheet, develops a simple spreadsheet applicaon. The
spreadsheet funconality will be enrely implemented in JavaScript plus jQuery UI, but
on the server-side, we will encounter the applicaon server, CherryPy, for the rst me
and we will extend it with Python code to deliver the page that contains the spreadsheet
applicaon dynamically.
www.it-ebooks.info
Preface
[ 2 ]
Chapter 3, Tasklist I: Persistence, a full edged web applicaon needs funconality to store
informaon on the server and a way to idenfy dierent users. In this chapter, we address
both issues as we develop a simple applicaon to maintain lists of tasks.
Chapter 4, Tasklist II: Databases and AJAX, refactors the tasklist applicaon developed in
framework and thereby our CRM applicaon by taking a look at browsing, ltering,
and sorng large numbers of enes. We also take a look at what is needed to allow
customizaon by the end user of the applicaon's appearance and its funconality.
www.it-ebooks.info
Preface
[ 3 ]
Appendix A, References to Resources, is a convenient overview of both Web and paper
resources.
What you need for this book
Besides a computer running Windows or Linux to develop and test your applicaons, you will
need the following pieces of open source soware:
Python 3.2
CherryPy 3.2.0
jQuery 1.4.4
jQuery UI 1.8.6
How to obtain and install these packages is explained in detail in Chapter 2. We also use
some addional plugins for jQuery and provide installaon instrucons where appropriate.
You will also need a web browser to interact with your applicaons. The applicaons were
tested on Firefox 3 and Internet Explorer 8, but any moderately recent versions of these
browsers will probably work just as well, as will Chrome. The Firebug extension for Firefox,
however, is a superior tool to debug the client-side of web applicaons, so you might want to
try it if you have not done so already. Appendix A provides links to the necessary resources.
Finally, you will need a text editor, preferably with syntax highlighng capabilies for Python
as well as JavaScript and HTML. The author uses Notepad++ (
http://notepad-plus-
plus.org/
) on Windows and JOE (http://joe-editor.sourceforge.net/) on Linux,
but the choice is enrely up to you.
Who this book is for
Moderately experienced Python programmers who want to learn how to create fairly
Code words in text are shown as follows: "Running CherryPy's
setup.py script installs a
number of modules in Python's Lib\site-packages directory."
A block of code is set as follows:
<div id="main">
<ul>
<li>one</li>
<li class="highlight">two</li>
<li>three</li>
</ul>
www.it-ebooks.info
Preface
[ 5 ]
</div>
<div id="footer">footer text</div>
When we wish to draw your aenon to a parcular part of a code block, the relevant lines
or items are set in bold:
t=t+'<thead class="ui-widget-header">
<tr class="ui-helper-reset"><th></th>';
for(i=0;i<opts.cols;i=i+1){
t=t+'<th class="ui-helper-reset">' +
String.fromCharCode(65+i)+"</th>";
}
Any command-line input or output is wrien as follows:
python -c "import cherrypy"
New terms and important words are shown in bold. Words that you see on the screen, in
menus or dialog boxes for example, appear in the text like this: "New books or authors may
be added by clicking the Add new buon."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
nd any errata, please report them by vising
http://www.packtpub.com/support,
selecng your book, clicking on the errata submission form link, and entering the details
of your errata. Once your errata are veried, your submission will be accepted and the
errata will be uploaded on our website, or added to any list of exisng errata, under the
Errata secon of that tle. Any exisng errata can be viewed by selecng your tle from
http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt,
we take the protecon of our copyright and licenses very seriously. If you come across any
illegal copies of our works, in any form, on the Internet, please provide us with the locaon
address or website name immediately so that we can pursue a remedy.
Please contact us at
[email protected] with a link to the suspected pirated material.
We appreciate your help in protecng our authors, and our ability to bring you valuable
content.
Questions
You can contact us at [email protected] if you are having a problem with any
aspect of the book, and we will do our best to address it.
www.it-ebooks.info
1
Choosing Your Tools
In this chapter, we look at the many aspects of designing web applicaons.
The idea is to provide you with an overview that may help you recognize
components in subsequent chapters and give you some insight into the
arguments used to decide which tool or library to use.
Also, as this book covers more than just developing example applicaons, we
illustrate some issues that are relevant when designing an applicaon that does
not deal with coding directly, like security or usability.
In this chapter, we will be:
implementaon language to use. We select Python as the language to implement
the server-side code but if we had compelling arguments to switch to C#, we could
do so without the need to change anything on the client.
If we zoom in on our web applicaon, an image emerges of many interacng layers, each
encapsulang a well dened piece of funconality. Everywhere two layers touch, informaon
ows through a well dened interface (API). This helps in the separaon of concepts (our
applicaon is only talking to the database layer to store and retrieve persistent data and only
to the web server to return data upon request) but in pracce, the separaon between these
layers isn't completely clear in all circumstances. For example, the server-side part of our
applicaon is actually an integral part of the web server.
This simple schemac of a web applicaon is virtually idencal to a regular client-server
architecture. However, when we look more closely at the implementaon of the client and
the interacon between client and server, dierences will emerge as we will see in the next
secon where we zoom in a bit closer.
www.it-ebooks.info
Chapter 1
[ 9 ]
What just happened?
With both halves of the applicaon idened, we can now zoom in on each individual half.
This will enable us to get a more detailed image, that will help us to make informed decisions
regarding the smaller components that make up our applicaon.
The main components are easy to idenfy:
The data store holds data on the server (it is oen a database engine, somemes
just les on the lesystem).
The server-side applicaon services requests that are passed through from the web
server.
The web server forwards those responses to the client again and may serve stac
les as well.
The web browser takes care of running the client side of the applicaon, but within the
browser, we can idenfy several layers of acvies. These consist of:
well develop your applicaon on your own Linux box, but test and deploy it on a Windows
server. The laer needs a license that will not be free, but even open source opons are not
always free. Many companies nowadays shi to deploying their applicaons to the cloud
and even though these machines might be running an open source operang system, you
pay not only for CPU power and bandwidth but also for support, the laer being crucial in
applicaons that will lose you money if they are not running. However, using open source
tools in general gives you a much wider choice because many tools run equally well on any
plaorm.
In the following secons, we will look at the many components that make up the tool chain
and will try to show what arguments were used for the choices made for developing the
applicaons in this book and what (if any) viable alternaves are there. Note that some
arguments are quite subjecve and the choice nally made does not necessarily indicate that
the alternave is bad; we certainly are not aempng to start ame wars over which tool is
beer. We simply list requirements for applicaon development as we see it and try to nd
the tools suitable for the task. In some situaons, another tool might be beer, but for this
book, we try to nd a matching toolset that can be used for all sample applicaons that are
free (as in beer) and easy to learn and use.
www.it-ebooks.info