Python 3 Web Development - Techprofree

Transcription

Python 3 Web DevelopmentBeginner's GuideUse Python to create, theme, and deploy unique webapplicationsMichel AndersBIRMINGHAM - MUMBAIwww.it-ebooks.info

Python 3 Web DevelopmentBeginner's GuideCopyright 2011 Packt PublishingAll rights reserved. No part of this book may be reproduced, stored in a retrieval system,or transmitted in any form or by any means, without the prior written permission of thepublisher, except in the case of brief quotations embedded in critical articles or reviews.Every effort has been made in the preparation of this book to ensure the accuracy of theinformation presented. However, the information contained in this book is sold withoutwarranty, either express or implied. Neither the author, nor Packt Publishing, and its dealersand distributors will be held liable for any damages caused or alleged to be caused directly orindirectly by this book.Packt Publishing has endeavored to provide trademark information about all of thecompanies and products mentioned in this book by the appropriate use of capitals. However,Packt Publishing cannot guarantee the accuracy of this information.First published: May 2011Production Reference: 1060511Published by Packt Publishing Ltd.32 Lincoln RoadOltonBirmingham, B27 6PA, UK.ISBN 978-1-849513-74-6www.packtpub.comCover Image by Rakesh Shejwal (shejwal.rakesh@gmail.com)www.it-ebooks.info

CreditsAuthorMichel AndersReviewersMichael DriscollRóman JoostTomi JuholaAndrew NicholsonProject CoordinatorsPoorvi NairMichelle QuadrosProofreaderMario CecereIndexerTejal DaruwaleHerjend TenyGraphicsAcquisition EditorNilesh MohiteSarah CullingtonProduction CoordinatorDevelopment EditorKruthika BangeraNeha MallikCover WorkTechnical EditorsKruthika BangeraSakina KaydawalaGauri IyerCopy EditorLeonard D'Silvawww.it-ebooks.info

About the AuthorMichel Anders, after his chemistry and physics studies where he spent more time oncomputer simulations than on real world experiments, the author found his real interestslay with IT and Internet technology, and worked as an IT manager for several differentcompanies, including an Internet provider, a hospital, and a software development company.After his initial exposure to Python as the built-in scripting language of Blender, the popular3D 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 writing his first book, Blender 2.49Scripting (Packt Publishing, 978-1-849510-40-0).He loves to help people with Blender and Python-related questions and may be contacted as'varkenvarken' at http://www.blenderartists.org/ and maintains a blog on Pythonspecific subjects at http://michelanders.blogspot.com/.For Clementine, always.www.it-ebooks.info

About the ReviewersMichael Driscoll has been programming Python since the Spring of 2006 and hasdabbled in other languages since the late nineties. He graduated from the University witha Bachelors of Science degree, majoring in Management Information Systems. Michaelenjoys programming for fun and profit. His hobbies include Biblical apologetics, bloggingabout Python at http://www.blog.pythonlibrary.org/, and learning photography.Michael currently works for the local government, where he does programming with Pythonas much as possible. Michael was also a Technical Reviewer for Python 3: Object OrientedProgramming by Dusty Phillips and Python Graphics Cookbook by Mike Ohlson de Fine (bothby Packt Publishing).I would like to thank my friends and family for their support and the funtimes they share with me. Most of all, I want to thank Jesus for saving mefrom myself.Róman Joost discovered open source software in 1997. He is the project manager foruser documentation for GNU Image Manipulation Program (GIMP). Róman also helped withGerman internationalization of GIMP. He has been contributing to GIMP and Zope opensource projects for eight years.Róman has a Diplom-Informatiker (FH) from the University of Applied Sciences in Koethen(Anhalt). He has worked for Zope companies—Gocept GmbH & Co in Germany, Infrae inThe Netherlands, and is currently working for a Zope company in Brisbane, Australia. Forrelaxation, he enjoys photography and digital painting with GIMP.www.it-ebooks.info

Tomi Juhola is a software development professional from Finland. He has a wide range ofdevelopment experience from embedded systems to modern distributed enterprise systemsin various roles such as tester, developer, consultant, and trainer.Currently, he works in a financial company and shares this time between development leadduties and helping other projects to adopt Scrum and Agile methodologies. He likes to spendhis free time with new interesting development languages and frameworks.He has reviewed conference proposals, a Python development book, and has also publishedhis own Master's theses on Agile embedded development.Andrew Nicholson is a computer engineer with over fourteen years of professionalexperience in a broad range of computing technologies. He is currently a Technical Directorwith Infinite Recursion Pty Ltd.—a bespoke software engineering company located in Sydney,Australia. He is a passionate advocate and a participant in the free, libre, and open sourcesoftware (FLOSS) community and has actively participated since 1999 contributing code,ideas, and energy in this engineering community. He was a Technical Reviewer for the bookPython Testing: Beginner's Guide (2010), Packt Publishing.Nicholson has a B.Eng (Computer) [Honours 1] from Newcastle University, Australia and aM.Eng (Wireless) with Merit from Sydney University, Australia.Nicholson's biography can be read at -ebooks.info

www.PacktPub.comSupport files, eBooks, discount offers, and moreYou might want to visit www.PacktPub.com for support files and downloads related to yourbook.Did you know that Packt offers eBook versions of every book published, with PDF and ePubfiles available? You can upgrade to the eBook version at www.PacktPub.com and as a printbook customer, you are entitled to a discount on the eBook copy. Get in touch with us atservice@packtpub.com for more details.At www.PacktPub.com, you can also read a collection of free technical articles, sign up for arange of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.http://PacktLib.PacktPub.comDo you need instant solutions to your IT questions? PacktLib is Packt's online digital booklibrary. Here, you can access, read and search across Packt's entire 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 browserFree Access for Packt account holdersIf you have an account with Packt at www.PacktPub.com, you can use this to accessPacktLib today and view nine entirely free books. Simply use your login credentials forimmediate access.www.it-ebooks.info

www.it-ebooks.info

Table of ContentsPrefaceChapter 1: Choosing Your Tools17Identifying the components of a web applicationTime for action – getting an overview of a web applicationChoosing suitable toolsTime for action – choosing a delivery framework, also known as web serverTime for action – choosing a server-side scripting languageTime for action – choosing a database engineTime for action – deciding on object relational mappersTime for action – choosing a presentation frameworkDesigning for maintainability and usabilityTestingTime for action – choosing a test frameworkVersion managementUsabilityGood looking – adhering to common GUI paradigmsThemableCross-browser compatibleCross-platform 021212222Standards compliant22Security23ReliableRobustAccess control and authenticationConfidentialityIntegrityA final word on security232324242525Help, I am confused!Time for action – maintaining overviewSummarywww.it-ebooks.info252628

Table of ContentsChapter 2: Creating a Simple SpreadsheetPython 3Time for action – installing Python 3 CherryPyTime for action – installing CherryPyInstalling jQuery and jQuery UIServing an applicationTime for action – serving a dummy applicationTime for action – serving HTML as dynamic contentWho serves what: an overviewHTML: separating form and contentTime for action – a unit convertorHTML: form-based interactionJavaScript: using jQuery UI widgetsTime for action – conversion using unitconverter.jsjQuery selectorsCSS: applying a jQuery UI theme to other elementsTime for action – converting a unit convertor into a pluginJavaScript: creating a jQuery UI pluginDesigning a spreadsheet applicationTime for action – serving a spreadsheet applicationHTML: keeping it simpleJavaScript: creating a spreadsheet pluginThe missing partsSummaryChapter 3: Tasklist I: 15252585859Designing a tasklist applicationTime for action – creating a logon screenServing a logon screenSetting up a sessionExpiring a sessionDesigning a task listTime for action – running tasklist.pyPython: the task moduleTime for action – implementing the task moduleAdding new tasksDeleting a taskJavaScript: tasklist.jsTime for action – styling the buttonsJavaScript: tooltip.jsTime for action – implementing inline labels[ ii ]www.it-ebooks.info596269707172727576808183838586

Table of ContentsCSS: tasklist.cssSummary8790Chapter 4: Tasklist II: Databases and AJAXThe advantages of a database compared to a filesystemChoosing a database engineDatabase-driven authenticationTime for action – authentication using a databaseTasklist II – storing tasks in a databaseImproving interactivity with AJAX91929293949999Time for action – getting the time with AJAXRedesigning the Tasklist applicationDatabase designTime for action – creating the task databaseTime for action – retrieving information with select statementsTaskDB – interfacing with the databaseTime for action – connecting to the databaseTime for action – storing and retrieving informationTime for action – updating and deleting informationTestingTime for action – testing factorial.pyNow what have we gained?Time for action – writing unit tests for tasklistdb.pyDesigning for AJAXClick 120The applicationTime for action – putting it all togetherHave a go hero – refreshing the itemlist on a regular basisSummaryChapter 5: Entities and Relations121123125126127Designing a book databaseThe Entity classTime for action – using the Entity classTime for action – creating instancesThe Relation classTime for action – using the Relation classRelation instancesTime for action – defining the Books databaseThe delivery layerTime for action – designing the delivery layerTime for action – adding a new book[ iii 62

Table of ContentsAuto completionTime for action – using input fields with auto completionThe presentation layerTime for action – using an enhanced presentation layerSummaryChapter 6: Building a Wiki165166168168170171The data layerTime for action – designing the wiki data modelThe delivery layerTime for action – implementing the opening screenThe structural componentsThe application methodsTime for action – implementing a wiki topic screenTime for action – editing wiki topicsAdditional functionalityTime for action – selecting an imageTime for action – implementing a tag cloudTime for action – searching for wordsThe importance of input validationTime for action – scrubbing your contentTime for action – rendering contentSummaryChapter 7: Refactoring Code for 201203Time for action – taking a critical lookRefactoringTime for action – defining new entities: how it should lookMetaclassesTime for action – using metaclassesMetaEntity and AbstractEntity classesTime for action – implementing the MetaEntity and AbstractEntity classesRelationsTime for action – defining new relations: how it should lookImplementing the MetaRelation and AbstractRelation classesAdding new methods to existing classes203205205206207208209217217219222Browsing lists of entitiesTime for action – using a table-based Entity browserTime for action – examining the HTML markupCachingThe books application revisitedTime for action – creating a books application, take twoSummary[ iv ]www.it-ebooks.info224224229232236236242

Table of ContentsChapter 8: Managing Customer RelationsA critical reviewDesigning a Customer Relationship Management applicationTime for action – implementing a basic CRMAdding and editing valuesTime for action – adding an instanceTime for action – editing an instanceAdding relationsPicklistsTime for action – implementing picklistsSummaryChapter 9: Creating Full-Fledged Webapps: Implementing InstancesEven more relationsTime for action – showing one-to-many relationshipsTime for action – adapting MetaRelationTime for action – enhancing DisplayTime for action – enhancing BrowseAccess controlTime for action – implementing access controlRole-based access controlTime for action – implementing role-based access controlSummaryChapter 10: Customizing the CRM ApplicationTime for action – sortingTime for action – filteringCustomizationTime for action – customizing entity displaysTime for action – customizing entity listsTime for action – adding a delete 302Appendix A: References to Resources303Good old offline reference booksAdditional websites, wikis, and blogs303304Appendix B: Pop Quiz Answers307Chapter 2, Creating a Simple SpreadsheetChapter 3, Tasklist I: PersistenceChapter 4, Tasklist II: Databases and AJAXChapter 5, Entities and RelationsChapter 6, Building a WikiIndex307308309310310311[v]www.it-ebooks.info

www.it-ebooks.info

PrefaceBuilding your own Python web applications provides you with the opportunity to have greatfunctionality, with no restrictions. However, creating web applications with Python is notstraightforward. Coupled with learning a new skill of developing web applications, you wouldnormally have to learn how to work with a framework as well.Python 3 Web Development Beginner's Guide shows you how to independently build yourown web application that is easy to use, performs smoothly, and is themed to your taste—allwithout having to learn another web framework.Web development can take time and is often fiddly to get right. This book will show youhow to design and implement a complex program from start to finish. Each chapter looksat a different type of web application, meaning that you will learn about a wide varietyof features and how to add them to your customized web application. You will also learnto implement jQuery into your web application to give it extra functionality. By using theright combination of a wide range of tools, you can have a fully functional, complex webapplication up and running in no time.A practical guide to building and customizing your own Python web application, without therestriction of a pre-defined framework.What this book coversChapter 1, Choosing Your Tools, looks at the many aspects of designing web applications.The idea is to provide you with an overview that may help you recognize components insubsequent chapters and give you some insight into the arguments used to decide whichtool or library to use. We also illustrate some issues that are relevant when designing anapplication that does not deal with coding directly, such as security or usability.Chapter 2, Creating a Simple Spreadsheet, develops a simple spreadsheet application. Thespreadsheet functionality will be entirely implemented in JavaScript plus jQuery UI, buton the server-side, we will encounter the application server, CherryPy, for the first timeand we will extend it with Python code to deliver the page that contains the spreadsheetapplication dynamically.www.it-ebooks.info

PrefaceChapter 3, Tasklist I: Persistence, a full fledged web application needs functionality to storeinformation on the server and a way to identify different users. In this chapter, we addressboth issues as we develop a simple application to maintain lists of tasks.Chapter 4, Tasklist II: Databases and AJAX, refactors the tasklist application developed inthe previous chapter. We will use the SQLite database engine on the server to store itemsand will use jQuery's AJAX functionality to dynamically update the contents of the webapplication. On the presentation side, we will encounter jQuery UI's event system and willlearn how to react on mouse clicks.Chapter 5, Entities and Relations, most real life applications sport more than one entity andoften many of these entities are related. Modeling these relations is one of the strong pointsof a relational database. In this chapter, we will develop a simple framework to managethese entities and use this framework to build an application to maintain lists of books formultiple users.Chapter 6, Building a Wiki, develops a wiki application and in doing so we focus on twoimportant concepts in building web applications. The first one is the design of the data layer.The wiki application is quite complex, and in this chapter, we try to see where the limitationsin our simple framework lie. The second one is input validation. Any application that acceptsinput from all over the Internet should check the data it receives, and in this chapter, we lookat both client-side and server-side input validation.Chapter 7, Refactoring Code for Reuse, after doing a substantial bit of work, it is often a goodidea to take a step back and look critically at your own work to see if things could have beendone better. In this chapter, we look at ways to make the entity framework more generallyuseful and employ it to implement the books application a second time.Chapter 8, Managing Customer Relations, there is more to an entity framework and CherryPyapplication code than merely browsing lists. The user must be able to add new instances andedit existing ones. This chapter is the start of the development of a CRM application that willbe extended and refined in the final chapters.Chapter 9, Creating Full-Fledged Webapps: Implementing Instances, focuses on the designand implementation of the user interface components to add and maintain entities,and relations between entities, in a way that is independent of the type of entity. Thisfunctionality is immediately put to use in the CRM application that we develop. Managinguser privileges is another issue we encounter as we explore the concept of role-based accesscontrol.Chapter 10, Customizing the CRM Application, is the final chapter and it extends ourframework and thereby our CRM application by taking a look at browsing, filtering,and sorting large numbers of entities. We also take a look at what is needed to allowcustomization by the end user of the application's appearance and its functionality.[2]www.it-ebooks.info

PrefaceAppendix A, References to Resources, is a convenient overview of both Web and paperresources.What you need for this bookBesides a computer running Windows or Linux to develop and test your applications, you willneed the following pieces of open source software: Python 3.2 CherryPy 3.2.0 jQuery 1.4.4 jQuery UI 1.8.6How to obtain and install these packages is explained in detail in Chapter 2. We also usesome additional plugins for jQuery and provide installation instructions where appropriate.You will also need a web browser to interact with your applications. The applications weretested on Firefox 3 and Internet Explorer 8, but any moderately recent versions of thesebrowsers 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 applications, so you might want totry 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 highlighting capabilities for Pythonas well as JavaScript and HTML. The author uses Notepad (http://notepad-plusplus.org/) on Windows and JOE (http://joe-editor.sourceforge.net/) on Linux,but the choice is entirely up to you.Who this book is forModerately experienced Python programmers who want to learn how to create fairlycomplex, database-driven, cross browser compatible web applications that are maintainableand look good, will find this book of most use. All applications in the book are developedin Python 3, but experience with Python 2.x is sufficient to understand all examples.JavaScript plays an important supporting role in many of the example applications and someintroductory level knowledge of JavaScript might be useful, but is not strictly necessarybecause the focus is mainly on Python development and the JavaScript code is used eitheras building blocks or explained in such detail that anyone comfortable with Python should beable to understand it.[3]www.it-ebooks.info

PrefaceConventionsIn this book, you will find several headings appearing frequently.To give clear instructions of how to complete a procedure or task, we use:Time for action – heading1.Action 12.Action 23.Action 3Instructions often need some extra explanation so that they make sense, so they arefollowed with:What just happened?This heading explains the working of tasks or instructions that you have just completed.You will also find some other learning aids in the book, including:Pop quiz – headingThese are short multiple choice questions intended to help you test your own understanding.Have a go hero – headingThese set practical challenges and give you ideas for experimenting with what you havelearned.You will also find a number of styles of text that distinguish between different kinds ofinformation. Here are some examples of these styles, and an explanation of their meaning.Code words in text are shown as follows: "Running CherryPy's setup.py script installs anumber 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 [4]www.it-ebooks.info

Preface /div div id "footer" footer text /div When we wish to draw your attention to a particular part of a code block, the relevant linesor 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 written as follows:python -c "import cherrypy"New terms and important words are shown in bold. Words that you see on the screen, inmenus or dialog boxes for example, appear in the text like this: "New books or authors maybe added by clicking the Add new button."Warnings or important notes appear in a box like this.Tips and tricks appear like this.Reader feedbackFeedback from our readers is always welcome. Let us know what you think about thisbook—what you liked or may have disliked. Reader feedback is important for us todevelop titles that you really get the most out of.To send us general feedback, simply send an e-mail to feedback@packtpub.com, andmention the book title via the subject of your message.If there is a book that you need and would like to see us publish, please send us a note in theSUGGEST A TITLE form on www.packtpub.com or e-mail suggest@packtpub.com.If there is a topic that you have expertise in and you are interested in either writing orcontributing to a book, see our author guide on www.packtpub.com/authors.[5]www.it-ebooks.info

PrefaceCustomer supportNow that you are the proud owner of a Packt book, we have a number of things to help youto get the most from your purchase.Downloading the example code for this bookYou can download the example code files for all Packt books you have purchased from youraccount at http://www.PacktPub.com. If you purchased this book elsewhere, you canvisit http://www.PacktPub.com/support and register to have the files e-mailed directlyto you.ErrataAlthough we have taken every care to ensure the accuracy of our content, mistakes dohappen. If you find a mistake in one of our books—maybe a mistake in the text or thecode—we would be grateful if you would report this to us. By doing so, you can save otherreaders from frustration and help us improve subsequent versions of this book. If youfind any errata, please report them by visiting http://www.packtpub.com/support,selecting your book, clicking on the errata submission form link, and entering the detailsof your errata. Once your errata are verified, your submission will be accepted and theerrata will be uploaded on our website, or added to any list of existing errata, under theErrata section of that title. Any existing errata can be viewed by selecting your title fromhttp://www.packtpub.com/support.PiracyPiracy of copyright material on the Internet is an ongoing problem across all media. At Packt,we take the protection of our copyright and licenses very seriously. If you come across anyillegal copies of our works, in any form, on the Internet, please provide us with the locationaddress or website name immediately so that we can pursue a remedy.Please contact us at copyright@packtpub.com with a link to the suspected pirated material.We appreciate your help in protecting our authors, and our ability to bring you valuablecontent.QuestionsYou can contact us at questions@packtpub.com if you are having a problem with anyaspect of the book, and we will do our best to address it.[6]www.it-ebooks.info

1Choosing Your ToolsIn this chapter, we look at the many aspects of designing web applications.The idea is to provide you with an overview that may help you recognizecomponents in subsequent chapters and give you some insight into thearguments used to decide which tool or library to use.Also, as this book covers more than just developing example applications, weillustrate some issues that are relevant when designing an application that doesnot deal with coding directly, like security or usability.In this chapter, we will be: Indentifying the components that a web application consists of Choosing suitable tools Considering what designing for maintainability and usability impliesThere is a lot of ground to cover, so let's get started.Identifying the components of a web applicationA web application is not a monolithic object. In designing such an application, it mighthelp focus if you look at an application as a collection of related objects, each with its welldefined purpose. This can be done with multiple levels of detail and even the mile high viewmay already give some valuable insights.www.it-ebooks.info

Choosing Your ToolsTime for action – getting an overview of a web applicationFrom the following picture shown, it should be clear that a web application is not a singularthing. It consists of parts that reside on a server and parts that run on the computer of theuser. Both halves are just as important; although the server may hold the application dataand implement the logic to modify that data following requests from the user, the data isdisplayed by the part of the web application running in the browser on the client computerand the user signals his/her request by interacting with the user interface components in thebrowser, for example, by clicking on an "OK" button. Think about your application and consider both server and client-side. Theadvantage of looking at the individual halves is that we might make choicesthat are optimal for the specific half. Look at the general requirements for the client half. For example, because we wantto offer the user a sophisticated user interface, we opt for the jQuery UI library. Thisdecision does not touch the overall design decision on the server, because apartfrom delivering the files that the jQuery UI library consists of, the choice of userinterface library has no impact on the choice of the database engine or the serveroperating system for example. Look at the requirements for the server half. For example, consider whichimplementation language to use. We select Python as the language to implementthe server-side code but if we had compelling arguments to switch to C#, we coulddo so without the need to change anything on the client.If we zoom in on our web application, an image emerges of many interacting layers, eachencapsulating a well defined piece of functionality. Everywhere two layers touch, informationflows through a well defined interface (API). This helps in the separation of concepts (ourapplication is only talking to the database layer to store and retrieve persistent data and onlyto the web server to return data upon request) but in practice, the separation between theselayers isn't completely clear in all circumstances. For example, the server-side part of ourapplication is actually an integral part of the web server.This simple schematic of a web application is virtually identical to a regular client-serverarchitecture. However, when we look more closely at the implementation of the client andthe interaction between client and server, differences will emerge as we will see in the nextsection where we zoom in a bit closer.[8]www.it-ebooks.info

Chapter 1What just happened?With both halves of the application identified, 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 decisionsregarding the smaller components that make up our application.The main components are easy to identify: The data store holds data on the server (it is often a database engine, sometimesjust files on the filesystem). The server-side application services requests that are passed through from the webserver. The web server forwards those responses

Python Testing: Beginner's Guide (2010), Packt Publishing. Nicholson has a B.Eng (Computer) [Honours 1] from Newcastle University, Australia and a M.Eng