35,99 €
If you want to learn how best to utilize commonly found patterns and learn best practices in developing applications with Django, this is the book for you. This book, like Django itself, is accessible to amateur and professional developers alike and assumes little in the way of prior experience.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 281
Veröffentlichungsjahr: 2015
Copyright © 2015 Packt Publishing
All 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 the publisher, 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 the information presented. However, the information 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 information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: March 2015
Production reference: 1260315
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78398-664-4
www.packtpub.com
Cover image by Sandeep Somasekharan (<[email protected]>)
Author
Arun Ravindran
Reviewers
Shoubhik Bose
Kracekumar Ramaraju
Jai Vikram Singh Verma
Commissioning Editor
Taron Pereira
Acquisition Editor
Rebecca Youé
Content Development Editor
Mohammed Fahad
Technical Editor
Vivek Pala
Copy Editor
Rashmi Sawant
Project Coordinator
Danuta Jones
Proofreaders
Martin Diver
Maria Gould
Indexer
Tejal Soni
Graphics
Valentina D'silva
Abhinash Sahu
Production Coordinator
Komal Ramchandani
Cover Work
Komal Ramchandani
Arun Ravindran is an avid speaker and blogger who has been tinkering with Django since 2007 for projects ranging from intranet applications to social networks. He is a long-time open source enthusiast and Python developer. His articles and screencasts have been invaluable to the rapidly growing Django community. He is currently a developer member of the Django Software Foundation. Arun is also a movie buff and loves graphic novels and comics.
I wish to thank my wife, Vidya for her constant support and encouragement. I was writing this book at an exciting and challenging time because we were expecting our second child - Nihar. My daughter Kavya also had to endure several solitary days, as her dad devoted to writing.
A big thanks to all the wonderful people at Packt Publishing - Rebecca, Fahad, Vivek and many others who helped in the creation of this book. Truly appreciate the honest reviews by Krace, Shoubhik and Jai. Sincere thanks to Anil Menon for his inputs on the 'SuperBook' storyline. Eternally grateful to Sandy for letting us use his dazzling click of a Hummingbird titled 'Alive!' as the cover photo.
I express my unending appreciation of the entire Django and Python community for being open, friendly and incredibly collaborative. Without their hard work and generosity, we would not have the great tools and knowledge that we depend on everyday.
Last but not the least, special thanks to my parents and friends who have always been there to support me.
Shoubhik Bose is a development engineer at IBM India Software Labs in IBM's security division. When not in the office, he is an independent researcher on healthcare technologies and contributes without profit to a social enterprise healthcare start-up named Mission Arogya as an architect. In 2011, he co-authored the Springer paper Service Crawling in Cloud Computing. He loves to explore "new age" programming languages, platforms, and development frameworks.
Kracekumar Ramaraju is a geek and Python enthusiast. He uses Python for fun and profit. He currently works at Recruiterbox, where he uses Python and Django to build web applications and automate servers. He has worked on other frameworks, such as Flask. He has spoken at PyCon India and the BangPypers meetup group. He contributes to Python open source projects. He has a BTech degree in information technology. He occasionally blogs at http://kracekumar.com.
I would like to thank Arun Ravindran and Packt Publishing for giving me an opportunity to review this book.
Jai Vikram Singh Verma is a passionate entrepreneur and technologist. A computer science engineer by education, he runs his own start-up called Startup Labs Infotech Pvt. Ltd. in Jaipur, Rajasthan, India. With a total of 7+ years of experience in architecting and developing scalable web applications using Python, Django, and related technologies, he is well versed with the ins and outs of web development. Startup Labs does web and mobile product development for clients across the world, and they are also cooking some nifty tech products to be released under their own banner soon.
Apart from work, Jai likes playing table tennis, cooking, going for long walks (especially in Sydney), driving, and just chilling out with friends.
I would like to thank Packt Publishing for giving me the opportunity to review this awesome book.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled 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 collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
Django is one of the most popular web frameworks in use today. It powers large websites, such as Pinterest, Instagram, Disqus, and NASA. With a few lines of code, you can rapidly build a functional and secure website that can scale to millions of users.
This book attempts to share solutions to several common design problems faced by Django developers. Sometimes, there are several solutions but we often wonder whether there is a recommended approach. Experienced developers frequently use certain idioms while deliberately avoiding certain others.
This book is a collection of such patterns and insights. It is organized into chapters each covering a key area of the framework, such as Models, or an aspect of web development, such as Debugging. The focus is on building clean, modular, and more maintainable code.
Every attempt has been made to present up-to-date information and use the latest versions. Django 1.7 comes loaded with exciting new features, such as built-in schema migrations and app reloading. Python 3.4 is the bleeding edge of the language with several new modules, such as asyncio. Both, both of which have been used here.
Superheroes are a constant theme throughout the book. Most of the code examples are about building SuperBook—a social network of superheroes. As a novel way to present the challenges of a web development project, an exciting fictional narrative has been woven into each chapter in the form of story boxes.
Chapter 1, Django and Patterns, helps us understand Django better by telling us why it was created and how it has evolved over time. Then, it introduces design patterns, its importance, and several popular pattern collections.
Chapter 2, Application Design, guides us through the early stages of an application life cycle, such as gathering requirements and creating mockups. We will also see how to break your project into modular apps through our running project—SuperBook.
Chapter 3, Models, gives us insights into how models can be graphically represented, structured using several kinds of patterns, and later altered using migrations (built into Django 1.7).
Chapter 4, Views and URLs, shows us how function-based views evolved into class-based views with the powerful mixin concept, familiarizes us with useful view patterns, and teaches us how short and meaningful URLs are designed.
Chapter 5, Templates, walks us through the Django template language constructs explaining their design choices, suggests how to organize template files, introduces handy template patterns, and points to several ways in which Bootstrap can be integrated and customized.
Chapter 6, Admin Interface, shows us how to use Django's brilliant out-of-the box admin interface more effectively, and several ways to customize it, from enhancing the models to improving its default look and feel.
Chapter 7, Forms, illustrates the often confusing forms workflow, different ways of rendering forms, how to improve a form's appearance using crispy forms and various applied form patterns.
Chapter 8, Dealing with Legacy Code, tackles the common issues with legacy Django projects, such as identifying the right version, locating the files, where to start reading a large codebase, and how to enhance legacy code by adding new functionality.
Chapter 9, Testing and Debugging, gives us an overview of various testing and debugging tools and techniques, introduces test-driven development, mocking, logging, and debuggers.
Chapter 10, Security, familiarizes you with various web security threats and their countermeasures, and especially with how Django can protect you. Finally, a handy security checklist reminds you of commonly overlooked areas.
Chapter 11, Production-ready, introduces a crash course in deploying a public-facing application beginning with choosing your web stack, understanding hosting options, and walking through a typical deployment process. We go into the details of monitoring and performance at this stage.
Appendix, Python 2 versus Python 3, introduces Python 3 to Python 2 developers. Starting off by showing the most relevant differences, while working in Django, we then move on to the new modules and tools offered in Python 3.
You will just need a computer (PC or Mac) and Internet connectivity to start with. Then, ensure that the following are installed:
I recommend working on a Linux-based system such as Ubuntu or Arch Linux. If you are on Windows, you can work on a Linux virtual machine using Vagrant or VirtualBox. Here is a full disclosure: I prefer command-line interfaces, Emacs, and eggs sunny-side up.
Certain chapters might also require installing certain Python libraries or Django packages. They will be mentioned as, say—the factory_boy package. In most cases, they can be installed using pip as follows:
Hence, it is highly recommended that you first create a separate virtual environment, as mentioned in Chapter 2, Application Design.
This book is aimed at developers who want insights into building highly maintainable websites using Django. It will help you gain a deeper understanding of the framework, but it will also familiarize you with several web development concepts.
It will be useful for beginners and experienced Django developers alike. It assumes that you are familiar with Python and have completed a basic tutorial on Django (try the official polls tutorial or a video tutorial from http://arunrocks.com).
You do not have to be an expert in Django or Python. No prior knowledge of patterns is expected for reading this book. More specifically, this book is not about the classic Gang of Four patterns, though they might get mentioned.
A lot of practical information here might not be unique to just Django, but to web development in general. By the end of this book, you should be a more efficient and pragmatic web developer.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Pull requests and bug reports to the SuperBook project can be sent to https://github.com/DjangoPatternsBook/superbook.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy 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 any illegal copies of our works, in any form, on the Internet, please provide us with the location 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 protecting our authors, and our ability to bring you valuable content.
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.
In this chapter, we will talk about the following topics:
According to Bowei Gai's "World Startup Report," there were more than 136,000 Internet firms across the world in 2013, with more than 60,000 in America alone. Of these, 87 US companies are valued more than 1 billion dollars. Another study says that of 12,000 people aged between 18 and 30 in 27 countries, more than two-thirds see opportunities in becoming an entrepreneur.
This entrepreneurial boom in digital startups is primarily due to the tools and technologies of startups becoming cheap and ubiquitous. Creating a fully fledged web application takes a lot less time than it used to, thanks to powerful frameworks.
With a gentle learning curve, even first-time programmers can learn to create web applications easily. However, soon they would keep solving the same problems others have been facing again and again. This is where understanding patterns can really help save their time.
Every web application is different, like a piece of handcrafted furniture. You will rarely find a mass-produced one meeting all your needs perfectly. Even if you start with a basic requirement, such as a blog or a social network, your needs will slowly grow, and you can easily end up with a lot of half-baked solutions duct-taped onto a once-simple cookie cutter solution.
This is why web frameworks such as Django or Rails have become extremely popular. Frameworks speed up development and have all the best practices baked in. However, they are also flexible enough to give you access to just enough plumbing for the job. Today, web frameworks are ubiquitous and most programming languages have at least one end-to-end framework similar to Django.
Python probably has more web frameworks than most programming languages. A quick look at PyPi (Python Package Index) brings up an amazing 13,021 packages related to frameworks. For Django, the total is 5,467 packages.
The Python wiki lists over 54 active web frameworks with the most popular ones being Django, Flask, Pyramid, and Zope. Python also has a wide diversity in frameworks. The compact Bottle micro web-framework is just one Python file that has no dependencies and is surprisingly capable of creating a simple web application.
Despite these abundant options, Django has emerged as a big favorite by a wide margin. Djangosites.org lists over 4,700 sites written in Django, including famous success stories such as Instagram, Pinterest, and Disqus.
As the official description says, Django (https://djangoproject.com) is a high-level Python web framework that encourages rapid development and clean, pragmatic design. In other words, it is a complete web framework with batteries included, just like Python.
The out-of-the-box admin interface, one of Django's unique features, is extremely helpful for early data entry and testing. Django's documentation has been praised for being extremely well-written for an open source project.
Finally, Django has been battle-tested in several high traffic websites. It has an exceptionally sharp focus on security with protection against common attacks such as Cross-site scripting (XSS) and Cross-site request forgery (CSRF).
Although in theory, you can use Django to build any kind of web application, it might not be the best for every use case. For example, to build a real-time interface for web-based chat, you might want to use Tornado, while the rest of your web app can still be done in Django. Choose the right tool for the job.
Some of the built-in features, such as the admin interface, might sound odd if you are used to other web frameworks. To understand the design of Django, let's find out how it came into being.
When you look at the Pyramids of Egypt, you would think that such a simple and minimal design must have been quite obvious. In truth, they are products of 4,000 years of architectural evolution. Step Pyramids, the initial (and clunky) design, had six rectangular blocks of decreasing size. It took several iterations of architectural and engineering improvements until the modern, glazing, and long-lasting limestone structures were invented.
Looking at Django you might get a similar feeling. So, elegantly built, it must have been flawlessly conceived. On the contrary, it was the result of rewrites and rapid iterations in one of the most high-pressure environments imaginable—a newsroom!
In the fall of 2003, two programmers, Adrian Holovaty and Simon Willison, working at the Lawrence Journal-World newspaper, were working on creating several local news websites in Kansas. These sites, including LJWorld.com, Lawrence.com, and KUsports.com—like most news sites were not just content-driven portals chock-full of text, photos, and videos, but they also constantly tried to serve the needs of the local Lawrence community with applications, such as a local business directory, events calendar, classifieds, and so on.
This, of course, meant lots of work for Simon, Adrian, and later Jacob Kaplan Moss who had joined their team; with very short deadlines, sometimes with only a few hours' notice. Since it was the early days of web development in Python, they had to write web applications mostly from scratch. So, to save precious time, they gradually refactored out the common modules and tools into something called "The CMS."
Eventually, the content management parts were spun off into a separate project called the Ellington CMS, which went on to become a successful commercial CMS product. The rest of "The CMS" was a neat underlying framework that was general enough to be used to build web applications of any kind.
By July 2005, this web development framework was released as Django (pronounced Jang-Oh) under an open source Berkeley Software Distribution (BSD) license. It was named after the legendary jazz guitarist Django Reinhardt. And the rest, as they say, is history.
Due to its humble origins as an internal tool, Django had a lot of Lawrence Journal-World-specific oddities. To make Django truly general purpose, an effort dubbed "Removing the Lawrence" was already underway.
However, the most significant refactoring effort that Django developers had to undertake was called "Removing the Magic." This ambitious project involved cleaning up all the warts Django had accumulated over the years, including a lot of magic (an informal term for implicit features) and replacing them with a more natural and explicit Pythonic code. For example, the model classes used to be imported from a magic module called django.models.*, rather than directly importing them from the models.py module they were defined in.
At that time, Django had about a hundred thousand lines of code, and it was a significant rewrite of the API. On May 1, 2006, these changes, almost the size of a small book, were integrated into Django's development version trunk and released as Django release 0.95. This was a significant step toward the Django 1.0 milestone.
Every year, conferences called DjangoCons are held across the world for Django developers to meet and interact with each other. They have an adorable tradition of giving a semi-humorous keynote on "why Django sucks." This could be a member of the Django community, or someone who works on competing web frameworks or just any notable personality.
Over the years, it is amazing how Django developers took these criticisms positively and mitigated them in subsequent releases. Here is a short summary of the improvements corresponding to what once used to be a shortcoming in Django and the release they were resolved in:
Over time, Django has become one of most idiomatic Python codebases in public domain. Django source code is also a great place to learn a Python web framework's architecture.
To truly appreciate Django, you will need to peek under the hood and see the various moving parts inside. This can be both enlightening and overwhelming. If you are already familiar with this, you might want to skip this section.
How web requests are processed in a typical Django application
The preceding figure shows the simplified journey of a web request from a visitor's browser to your Django application and back. The numbered paths are as follows:
5a. Talks to a database via the models
5b. Renders HTML or any other formatted response using templates
5c. Returns a plain text response (not shown)
5d. Raises an exception
The HttpResponse object gets rendered into a string, as it leaves the Django application.A beautifully rendered web page is seen in your user's browser.Though certain details are omitted, this representation should help you appreciate Django's high-level architecture. It also show the roles played by the key components, such as models, views, and templates. Many of Django's components are based on several well-known design patterns.
What is common between the words "Blueprint," "Scaffolding," and "Maintenance"? These software development terms have been borrowed from the world of building construction and architecture. However, one of the most influential terms comes from a treatise on architecture and urban planning written in 1977 by the leading Austrian architect Christopher Alexander and his team consisting of Murray Silverstein, Sara Ishikawa, and several others.
The term "Pattern" came in vogue after their seminal work, A Pattern Language: Towns, Buildings, Construction (volume 2 in a five-book series) based on the astonishing insight that users know about their buildings more than any architect ever could. A pattern refers to an everyday problem and its proposed but time-tested solution.
In the book, Christopher Alexander states that "Each pattern describes a problem, which occurs over and over again in our environment, and then describes the core of the solution to that problem in such a way that you can use this solution a million times over, without ever doing it the same way twice."
For example, the Wings Of Light pattern describes how people prefer buildings with more natural lighting and suggests arranging the building so that it is composed of wings. These wings should be long and narrow, never more than 25 feet wide. Next time you enjoy a stroll through the long well-lit corridors of an old university, be grateful to this pattern.
Their book contained 253 such practical patterns, from the design of a room to the design of entire cities. Most importantly, each of these patterns gave a name to an abstract problem and together formed a pattern language.
Remember when you first came across the word déjà vu? You probably thought "Wow, I never knew that there was a word for that experience." Similarly, architects were not only able to identify patterns in their environment but could also, finally, name them in a way that their peers could understand.
In the world of software, the term design pattern refers to a general repeatable solution to a commonly occurring problem in software design. It is a formalization of best practices that a developer can use. Like in the world of architecture, the pattern language has proven to be extremely helpful to communicate a certain way of solving a design problem to other programmers.
There are several collections of design patterns but some have been considerably more influential than the others.
One of the earliest efforts to study and document design patterns was a book titled