logo资料库

Pro Django (2nd edition).pdf

第1页 / 共290页
第2页 / 共290页
第3页 / 共290页
第4页 / 共290页
第5页 / 共290页
第6页 / 共290页
第7页 / 共290页
第8页 / 共290页
资料共290页,剩余部分请下载后查看
Pro Django
Contents at a Glance
Contents
About the Author
About the Technical Reviewers
Acknowledgments
Preface
Introduction
Chapter 1: Understanding Django
Philosophy
Django’s Interpretation of the MVC Pattern
Model
Template
URL Configuration
Loose Coupling
Don’t Repeat Yourself (DRY)
A Focus on Readability
Failing Loudly
Documenting Rules
Community
Management of the Framework
News and Resources
Reusable Applications
Getting Help
Read the Documentation
Check Your Version
Frequently Asked Questions (FAQ)
Mailing Lists
Internet Relay Chat (IRC)
Now What?
Chapter 2: Django Is Python
How Python Builds Classes
Building a Class Programmatically
Metaclasses Change It Up
Using a Base Class with a Metaclass
Declarative Syntax
Centralized Access
The Base Class
Attribute Classes
Ordering Class Attributes
Class Declaration
Common Duck Typing Protocols
Callables
__call__(self[, …])
Dictionaries
__contains__(self, key)
__getitem__(self, key)
__setitem__(self, key, value)
Files
read(self, [size])
write(self, str)
close(self)
Iterables
__iter__(self)
Iterators
next(self)
Generators
Sequences
__len__(self)
__getitem__(self) and __setitem__(self, value)
Augmenting Functions
Excess Arguments
Positional Arguments
Keyword Arguments
Mixing Argument Types
Passing Argument Collections
Decorators
Decorating with Extra Arguments
Partial Application of Functions
Back to the Decorator Problem
A Decorator with or without Arguments
Descriptors
__get__(self, instance, owner)
__set__(self, instance, value)
Keeping Track of Instance Data
Introspection
Common Class and Function Attributes
Identifying Object Types
Getting Arbitrary Object Types
Checking for Specific Types
Function Signatures
Handling Default Values
Docstrings
Applied Techniques
Tracking Subclasses
A Simple Plugin Architecture
Now What?
Chapter 3: Models
How Django Processes Model Classes
Setting Attributes on Models
Getting Information About Models
Class Information
Field Definitions
Primary Key Fields
Configuration Options
Accessing the Model Cache
Retrieving All Applications
Retrieving a Single Application
Dealing with Individual Models
Using Model Fields
Common Field Attributes
Common Field Methods
Subclassing Fields
Deciding Whether to Invent or Extend
Performing Actions During Model Registration
contribute_to_class(self, cls, name)
contribute_to_related_class(self, cls, related)
Altering Data Behavior
get_internal_type(self)
validate(self, value, instance)
to_python(self, value)
Supporting Complex Types with SubfieldBase
Controlling Database Behavior
db_type(self, connection)
get_prep_value(self, value)
get_db_prep_value(self, value, connection, prepared=False)
get_db_prep_save(self, value, connection)
get_prep_lookup(self, lookup_type, value)
get_db_prep_lookup(self, lookup_type, value, connection, prepared=False)
Dealing with Files
get_directory_name(self)
get_filename(self, filename)
generate_filename(self, instance, filename)
save_form_data(self, instance, data)
delete_file(self, instance, sender)
attr_class
Customizing the File Class
path(self)
url(self)
size(self)
open(self, mode=‘rb’)
save(self, name, content, save=True)
delete(self, save=True)
Signals
class_prepared
pre_init and post_init
pre_save and post_save
pre_delete and post_delete
post_syncdb
Applied Techniques
Loading Attributes on Demand
Storing Raw Data
Pickling and Unpickling Data
Unpickling on Demand
Putting It All Together
Creating Models Dynamically at Runtime
A First Pass
Adding Model Configuration Options
Now What?
Chapter 4: URLs and Views
URLs
Standard URL Configuration
The patterns() Function
The url( ) Function
The include( ) Function
Resolving URLs to Views
Resolving Views to URLs
The permalink Decorator
The url Template Tag
The reverse( ) Utility Function
Function-Based Views
Templates Break It Up a Bit
Anatomy of a View
Writing Views to Be Generic
Use Lots of Arguments
Provide Sensible Defaults
View Decorators
Applying View Decorators
Writing a View Decorator
Class-Based Views
django.views.generic.base.View
__init__(self, **kwargs)
as_view(cls, **initkwargs)
dispatch(self, request, *args, **kwargs)
Individual View Methods
Decorating View Methods
Using an Object As a View
Applied Techniques
Cross-Origin Resource Sharing (CORS)
CORS Decorator
CORS Mixin
Providing Both a Decorator and a Mixin
Now What?
Chapter 5: Forms
Declaring and Identifying Fields
Binding to User Input
Validating Input
Using Class-Based Views
Custom Fields
Validation
Controlling Widgets
Defining HTML Behavior
Custom Widgets
Rendering HTML
Obtaining Values from Posted Data
Splitting Data Across Multiple Widgets
Customizing Form Markup
Accessing Individual Fields
Customizing the Display of Errors
Applied Techniques
Pending and Resuming Forms
Storing Values for Later
Reconstituting a Form
A Full Workflow
Making It Generic
A Class-Based Approach
Now What?
Chapter 6: Templates
What Makes a Template
Exceptions
The Process at Large
Content Tokens
Parsing Tokens into Nodes
Template Nodes
Rendering Templates
Context
Simple Variable Resolution
Complex Variable Lookup
Including Aspects of the Request
Retrieving Templates
django.template.loader.get_template(template_name)
django.template.loader.select_template(template_name_list)
Shortcuts to Load and Render Templates
render_to_string(template_name, dictionary=None, context_instance=None)
render_to_response(template_name, dictionary=None, context_instance=None, content_type=None)
Adding Features for Templates
Setting Up the Package
Variable Filters
Accepting a Value
Accepting an Argument
Returning a Value
Registering As a Filter
Template Tags
A Simple Tag
A Shortcut for Simple Tags
Adding Features to All Templates
Applied Techniques
Embedding Another Template Engine
Converting a Token to a String
Compiling to a Node
Preparing the Jinja Template
Enabling User-Submitted Themes
Setting Up the Models
Supporting Site-Wide Themes
Setting Up Templates to Use Themes
Validating and Securing Themes
An Example Theme
Now What?
Chapter 7: Handling HTTP
Requests and Responses
HttpRequest
HttpRequest.method
“Safe” Methods
“Idempotent” Methods
HttpRequest.path
Accessing Submitted Data
HttpRequest.GET
HttpRequest.POST
HttpRequest.FILES
HttpRequest.raw_post_data
HttpRequest.META
HttpRequest.COOKIES
HttpRequest.get_signed_cookie(key[, …])
HttpRequest.get_host( )
HttpRequest.get_full_path( )
HttpRequest.build_absolute_uri(location=None)
HttpRequest.is_secure( )
HttpRequest.is_ajax( )
HttpRequest.encoding
HttpResponse
Creating a Response
Dictionary Access to Headers
File-Like Access to Content
HttpResponse.status_code
HttpResponse.set_cookie(key, value=''[, …])
HttpResponse.delete_cookie(key, path='/', domain=None)
HttpResponse.cookies
HttpResponse.set_signed_cookie(key, value, salt=''[, …])
HttpResponse.content
Specialty Response Objects
Writing HTTP Middleware
MiddlewareClass.process_request(self, request)
MiddlewareClass.process_view(self, request, view, args, kwargs)
MiddlewareClass.process_response(self, request, response)
MiddlewareClass.process_exception(self, request, exception)
Deciding Between Middleware and View Decorators
Differences in Scope
Configuration Options
Using Middleware As Decorators
Allowing Configuration Options
HTTP-Related Signals
django.core.signals.request_started
django.core.signals.request_finished
django.core.signals.got_request_exception
Applied Techniques
Signing Cookies Automatically
Signing Outgoing Response Cookies
Validating Incoming Request Cookies
Signing Cookies As a Decorator
Now What?
Chapter 8: Backend Protocols
Database Access
django.db.backends
DatabaseWrapper
DatabaseWrapper.features
DatabaseWrapper.ops
Comparison Operators
Obtaining a Cursor
Creation of New Structures
Introspection of Existing Structures
DatabaseClient
DatabaseError and IntegrityError
Authentication
get_user(user_id)
authenticate(**credentials)
Storing User Information
Files
The Base File Class
Handling Uploads
Storing Files
Session Management
Caching
Specifying a Backend
Using the Cache Manually
Template Loading
load_template_source(template_name, template_dirs=None)
load_template_source.is_usable
load_template(template_name, template_dirs=None)
Context Processors
Applied Techniques
Scanning Incoming Files for Viruses
Now What?
Chapter 9: Common Tools
Core Exceptions (django.core.exceptions)
ImproperlyConfigured
MiddlewareNotUsed
MultipleObjectsReturned
ObjectDoesNotExist
PermissionDenied
SuspiciousOperation
ValidationError
ViewDoesNotExist
Text Modification (django.utils.text)
compress_string(s)
compress_sequence(sequence)
get_text_list(items, last_word='or')
javascript_quote(s, quote_double_quotes=False)
normalize_newlines(text)
phone2numeric(phone)
recapitalize(text)
slugify(value)
smart_split(text)
unescape_entities(text)
unescape_string_literal(s)
wrap(text, width)
Truncating Text
Truncator.chars(num, truncate='…')
Truncator.words(num, truncate='…', html=False)
Data Structures (django.utils.datastructures)
DictWrapper
ImmutableList
MergeDict
MultiValueDict
SortedDict
Functional Utilities (django.utils.functional)
cached_property(func)
curry(func)
lazy(func, *resultclasses)
allow_lazy(func, *resultclasses)
lazy_property(fget=None, fset=None, fdel=None)
memoize(func, cache, num_args)
partition(predicate, values)
wraps(func)
Signals
How It Works
Defining a Signal
Sending a Signal
Capturing Return Values
Defining a Listener
Registering Listeners
Forcing Strong References
Now What?
Chapter 10: Coordinating Applications
Contacts
contacts.models.Contact
contacts.forms.UserEditorForm
contacts.forms.ContactEditorForm
contacts.views.EditContact
Admin Configuration
URL Configuration
Real Estate Properties
properties.models.Property
properties.models.Feature
properties.models.PropertyFeature
properties.models.InterestedParty
Admin Configuration
URL Configuration
Now What?
Chapter 11: Enhancing Applications
Adding an API
Serializing Data
Outputting a Single Object
Handling Relationships
Controlling Output Fields
Many-to-Many Relationships
Getting the Appropriate Fields
Getting Information About the Relationship
Retrieving Data
ResourceView
ResourceListView
ResourceDetailView
Now What?
Index
For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them.
Contents at a Glance About the Author �������������������������������������������������������������������������������������������������������������� xvii About the Technical Reviewers ����������������������������������������������������������������������������������������� xix Acknowledgments ������������������������������������������������������������������������������������������������������������� xxi Preface ���������������������������������������������������������������������������������������������������������������������������� xxiii Introduction ���������������������������������������������������������������������������������������������������������������������� xxv ■ Chapter 1: Understanding Django ��������������������������������������������������������������������������������������1 ■ Chapter 2: Django Is Python ��������������������������������������������������������������������������������������������11 ■ Chapter 3: Models �����������������������������������������������������������������������������������������������������������41 ■ Chapter 4: URLs and Views ����������������������������������������������������������������������������������������������83 ■ Chapter 5: Forms �����������������������������������������������������������������������������������������������������������107 ■ Chapter 6: Templates �����������������������������������������������������������������������������������������������������131 ■ Chapter 7: Handling HTTP ����������������������������������������������������������������������������������������������157 ■ Chapter 8: Backend Protocols ���������������������������������������������������������������������������������������175 ■ Chapter 9: Common Tools ����������������������������������������������������������������������������������������������201 ■ Chapter 10: Coordinating Applications ��������������������������������������������������������������������������225 ■ Chapter 11: Enhancing Applications �����������������������������������������������������������������������������247 Index ���������������������������������������������������������������������������������������������������������������������������������267 v
Introduction Pro Django represents seven years of accumulated knowledge in Python and Django, designed to educate readers who are already familiar with both topics and would like to take them further than they had previously done. You will learn a wide range of advanced techniques available in both Python and Django, along with tips on how to use them to achieve advanced functionality. This book is designed to be both a narrative to be read from start to finish and a general reference to be searched for specific information. Since you may not know what to look for or where to find it yet, feel free to read through the book first, then keep it handy for refreshing your memory as necessary. What This Book Is Not There are plenty of resources available for learning Python and Django, so this book does not strive to teach the basics. For readers new to Python, I highly recommend Dive Into Python 3 by Mark Pilgrim (Apress, 2009). For learning Django, I’d recommend The Definitive Guide to Django: Web Development Done Right by Adrian Holovaty and Jacob Kaplan-Moss (Second Edition, Apress, 2009). Additionally, Practical Django Projects by James Bennett (Second Edition, Apress, 2009) is an excellent resource for general application development. Who This Book Is For Because Pro Django doesn’t dwell on introductory details, readers will be expected to have experience with both Python and Django. If you’re new to either subject, please consider one of the books mentioned in the previous section before trying to tackle this book. Even if you’ve only experimented on your own without launching a full site yet, a basic familiarity should be sufficient. You don’t need to be an expert to start reading Pro Django, but you might be by the time you finish. Interpreting Code Samples Pro Django uses a simple format, interleaving explanations of Python’s and Django’s available features with code that demonstrates their use in the real world. There are two types of code samples used, which differ in how they should be executed. Python’s interactive interpreter is a great way to test out small pieces of code and see how it works in a variety of situations. Lines of code intended for use in that environment will always be prefixed with three characters: three greater-than signs (>>>) or three periods (. . .). Lines with greater-than signs are the outermost block of code, while the period-prefixed lines are indented at least one level. The three initial characters are also followed by a space. These first four characters are not typed into the interactive interpreter directly; they simply mimic what the interpreter itself looks like by reproducing its output. xxv
■ IntroduCtIon A line started with three periods but containing no other text indicates that you should simply press Enter on a blank line in the interpreter. This completes any open code blocks, bringing you back to the >>> prompt. Any lines that don’t begin with either >>> or . . . represent the output of the code or the result of the previous expression. >>> import django >>> django.get_version() '1.5.1' The first line of an interactive example will always begin with >>>; everything else is code that should be written in a file and executed as part of a running Django application. The surrounding text will indicate what file the code should be placed in and how it will execute. Prerequisites Pro Django is written for Django 1.5, which was released on February 26, 2013. That release or a more recent clone of the Django code repository is required for the code samples to work properly. Since Django in turn relies on Python, these examples also assume a working Python environment of version 2.7 or higher. Most of the code examples are written with Python 3.3 in mind, but there are capability notes available where older versions diverge from the examples shown. xxvi
Chapter 1 Understanding Django Code alone isn’t enough. Sure, it’s what the computer runs, but code has to come from somewhere. A programmer has to sit down and decide what features to include, how they should be implemented, what other software to utilize, and how to provide hooks for future enhancements to be added. It’s easy to skip straight to code, ignoring the cognitive process that produces it, but great programmers always have reasons for the decisions they make. With a framework, like Django, many such decisions have already been made, and the tools provided are shaped by these decisions, and by the programmers who made them. By adopting these philosophies in your own code, not only will you be consistent with Django and other applications, but you may even be amazed at what you’re able to accomplish. Beneath even the simplest code is the thought process that went into its creation. Decisions were made about what it should do and how it should do it. This thought process is a step often overlooked in books and manuals, leading to an army of technicians slaving away, writing code that manages to accomplish the task at hand but without a vision for its future. While the rest of this book will explain in detail the many basic building blocks Django provides for even the most complicated of projects, this chapter will focus on even more fundamental aspects of the framework. For those readers coming from other backgrounds, the ideas presented in this chapter may seem considerably foreign, but that doesn’t make them any less important. All programmers working with Python and Django would do well to have a solid understanding of the reasons Django works the way it does, and how those principles can be applied to other projects. You may want to read this chapter more than once, and perhaps refer to it often as you work with Django. Many of the topics are common knowledge in the Django community, so reading this chapter carefully is essential if you plan to interact with other programmers. Philosophy Django relies heavily on philosophy, both in how its code is written and how decisions are made about what goes into the framework. This isn’t unique in programming, but it’s something newcomers often have trouble with. It is essential to maintain both consistency and quality, and having a set of common principles to refer to when making decisions helps maintain both. Since these concepts are also important to individual applications, and even collections of applications, a firm grasp on these philosophies will yield similar benefits. Perhaps the best-known and most-quoted passage of Python philosophy comes from Tim Peters, a longtime Python guru who wrote down many of the principles that guide Python’s own development process. The 19 lines he came up with, called the Zen of Python, have been so influential to Python programmers over time that they are immortalized as Python Enhancement Proposal (PEP) 201 and in the Python distribution itself, as an “Easter egg” module called this. 1http://prodjango.com/pep-20/ 1
Chapter 1 ■ Understanding django >>> import this Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! While some of this is clearly intended for humor, it sums up common Python attitudes pretty well. The remainder of this chapter highlights some specific principles that are often cited within the Django community, but all professional Python programmers should keep this text in mind and reference it often. One important thing to keep in mind is that many of the lines in the Zen of Python are subjective. For example, “beautiful” may be better than “ugly,” but definitions of “beautiful” are plentiful and can vary as much as the people who provide them. Similarly, consider notions of simplicity and complexity, practicality and purity; each developer will have a different opinion on which side of the line a particular piece of code should be placed. Django’s Interpretation of the MVC Pattern One of the most common application architectures—adopted by hobbyists and corporations alike—is the Model-View-Controller (MVC) pattern, as it provides clean separation of tasks and responsibilities between the prominent aspects of an application. Django only loosely follows this approach. A proper discussion should kick off with a quick overview of its components. • • The model is generally responsible for managing data and core business logic. The view displays that data to the user. The controller accepts user input and performs logic specific to the application.Although this pattern has proven very effective in many domains, Django’s authors weren’t looking to conform to any kind of pattern at the outset. They were simply interested in finding the most effective way to develop software for the Web. After all, Django was built for the daily needs of a working newspaper, where things have to happen very quickly if they’re to happen at all. Ultimately, the separation of tasks into discrete groups serves a few different purposes. • • Code that is designed for a specific set of tasks is much more maintainable because it doesn’t need to make assumptions about completely unrelated parts of the application. In general, this concept is called separation of concerns and is applicable throughout software development. Application development becomes more flexible, as multiple distinctly different view and controller layers may connect to a single model layer. This enables a variety of applications to share the same business logic and data, presenting it and interacting with it in different ways, for different audiences. 2
Chapter 1 ■ Understanding django • Developers are able to learn just those parts of the system that are pertinent to the work being performed. This specialization helps to curb frustration and fatigue, while fostering creativity and excellence within each developer’s domain of specialty. There are certainly other smaller benefits, but these are generally the main goals achieved with the use of MVC. It’s interesting to note, however, that the only part of those benefits that applies to any specific division in the MVC pattern is the ability to plug multiple applications into a single model layer. The rest is just an arbitrary division based on common development plans. Django’s developers sought these same benefits, but with an emphasis on rapid development, and after getting a set of tools that made sense for their workflow, they ended up with what some have called a Model-Template-View (MTV) pattern. However, there are really four primary code divisions in a Django application, which are outlined next. Model Given the benefit of keeping models apart from the rest of the application, Django follows that part of MVC to the letter. Django models provide easy access to an underlying data storage mechanism, and can also encapsulate any core business logic, which must always remain in effect, regardless of which application is using it. Models exist independent of the rest of the system, and are designed to be used by any application that has access to them. In fact, the database manipulation methods that are available on model instances can be utilized even from the interactive interpreter, without loading a Web server or any application-specific logic. Chapter 3 covers Django models in more detail, including how they’re defined and utilized, how to include your own business logic, and much more. ViewThough they share a name with the original MVC definition, Django views have little else in common with the traditional paradigm. Instead, they combine some of the traditional view’s responsibility with the entirety of the controller’s tasks. A view accepts user input (including simple requests for information), behaves according to the application’s interaction logic, and returns a display that is suitable for users to access the data represented by models. Views are normally defined as standard Python functions that are called when a user requests a specific URL. In terms of the Web, even a simple request for information is considered an action, so views are intended to handle that alongside data modifications and other submissions. Views can access the models, retrieving and updating information as necessary to accomplish the task requested by the user. Since views are simply called as functions, without requiring any specific structure, they can be specified in a number of ways. As well as a simple function, a view could take the form of any Python callable, including classes, instance methods, callable objects, and curried or decorated functions. Template While views are technically responsible for presenting data to the user, the task of how that data is presented is generally delegated to templates, which are an important enough part of Django development to be considered a separate layer entirely. Many have drawn a parallel between Django templates and the traditional view layer, since templates handle all the presentational details the user will see. Django provides a simple template language for this purpose, so that template designers don’t need to learn Python just to work with templates. Django’s template language is not dependent on any particular presentation language. It’s primarily used for HTML but can be used to generate any text-based format. Keep in mind, however, that this template engine is just one tool that views can use to render a display for a user. Many views may use HTTP redirects to other URLs, third-party Portable Document Format (PDF) libraries, or anything else to generate their output. 3
分享到:
收藏