售 价:¥
温馨提示:数字商品不支持退换货,不提供源文件,不支持导出打印
为你推荐
Title Page
Copyright and Credits
Learn Web Development with Python
About Packt
Why subscribe?
Packt.com
Contributors
About the authors
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
A Gentle Introduction to Python
A proper introduction
Enter the Python
About Python
Portability
Coherence
Developer productivity
An extensive library
Software quality
Software integration
Satisfaction and enjoyment
What are the drawbacks?
Who is using Python today?
Setting up the environment
Python 2 versus Python 3
Installing Python
Setting up the Python interpreter
About virtualenv
Your first virtual environment
Your friend, the console
How you can run a Python program
Running Python scripts
Running the Python interactive shell
Running Python as a service
Running Python as a GUI application
How is Python code organized?
How do we use modules and packages?
Python's execution model
Names and namespaces
Scopes
Objects and classes
Guidelines on how to write good code
The Python culture
A note on IDEs
Summary
Built-in Data Types
Everything is an object
Mutable or immutable? That is the question
Numbers
Integers
Booleans
Real numbers
Complex numbers
Fractions and decimals
Immutable sequences
Strings and bytes
Encoding and decoding strings
Indexing and slicing strings
String formatting
Tuples
Mutable sequences
Lists
Byte arrays
Set types
Mapping types – dictionaries
The collections module
namedtuple
defaultdict
ChainMap
Enums
Final considerations
Small values caching
How to choose data structures
About indexing and slicing
About the names
Summary
Iterating and Making Decisions
Conditional programming
A specialized else – elif
The ternary operator
Looping
The for loop
Iterating over a range
Iterating over a sequence
Iterators and iterables
Iterating over multiple sequences
The while loop
The break and continue statements
A special else clause
Putting all this together
A prime generator
Applying discounts
A quick peek at the itertools module
Infinite iterators
Iterators terminating on the shortest input sequence
Combinatoric generators
Summary
Functions, the Building Blocks of Code
Why use functions?
Reducing code duplication
Splitting a complex task
Hiding implementation details
Improving readability
Improving traceability
Scopes and name resolution
The global and nonlocal statements
Input parameters
Argument-passing
Assignment to argument names doesn't affect the caller
Changing a mutable affects the caller
How to specify input parameters
Positional arguments
Keyword arguments and default values
Variable positional arguments
Variable keyword arguments
Keyword-only arguments
Combining input parameters
Additional unpacking generalizations
Avoid the trap! Mutable defaults
Return values
Returning multiple values
A few useful tips
Recursive functions
Anonymous functions
Function attributes
Built-in functions
One final example
Documenting your code
Importing objects
Relative imports
Summary
Saving Time and Memory
The map, zip, and filter functions
map
zip
filter
Comprehensions
Nested comprehensions
Filtering a comprehension
dict comprehensions
set comprehensions
Generators
Generator functions
Going beyond next
The yield from expression
Generator expressions
Some performance considerations
Don't overdo comprehensions and generators
Name localization
Generation behavior in built-ins
One last example
Summary
OOP, Decorators, and Iterators
Decorators
A decorator factory
Object-oriented programming (OOP)
The simplest Python class
Class and object namespaces
Attribute shadowing
Me, myself, and I – using the self variable
Initializing an instance
OOP is about code reuse
Inheritance and composition
Accessing a base class
Multiple inheritance
Method resolution order
Class and static methods
Static methods
Class methods
Private methods and name mangling
The property decorator
Operator overloading
Polymorphism – a brief overview
Data classes
Writing a custom iterator
Summary
Files and Data Persistence
Working with files and directories
Opening files
Using a context manager to open a file
Reading and writing to a file
Reading and writing in binary mode
Protecting against overriding an existing file
Checking for file and directory existence
Manipulating files and directories
Manipulating pathnames
Temporary files and directories
Directory content
File and directory compression
Data interchange formats
Working with JSON
Custom encoding/decoding with JSON
IO, streams, and requests
Using an in-memory stream
Making HTTP requests
Persisting data on disk
Serializing data with pickle
Saving data with shelve
Saving data to a database
Summary
Testing, Profiling, and Dealing with Exceptions
Testing your application
The anatomy of a test
Testing guidelines
Unit testing
Writing a unit test
Mock objects and patching
Assertions
Testing a CSV generator
Boundaries and granularity
Testing the export function
Final considerations
Test-driven development
Exceptions
Profiling Python
When to profile?
Summary
Concurrent Execution
Concurrency versus parallelism
Threads and processes – an overview
Quick anatomy of a thread
Killing threads
Context-switching
The Global Interpreter Lock
Race conditions and deadlocks
Race conditions
Scenario A – race condition not happening
Scenario B – race condition happening
Locks to the rescue
Scenario C – using a lock
Deadlocks
Quick anatomy of a process
Properties of a process
Multithreading or multiprocessing?
Concurrent execution in Python
Starting a thread
Starting a process
Stopping threads and processes
Stopping a process
Spawning multiple threads
Dealing with race conditions
A thread's local data
Thread and process communication
Thread communication
Sending events
Inter-process communication with queues
Thread and process pools
Using a process to add a timeout to a function
Case examples
Example one – concurrent mergesort
Single-thread mergesort
Single-thread multipart mergesort
Multithreaded mergesort
Multiprocess mergesort
Example two – batch sudoku-solver
What is Sudoku?
Implementing a sudoku-solver in Python
Solving sudoku with multiprocessing
Example three – downloading random pictures
Downloading random pictures with asyncio
Summary
Debugging and Troubleshooting
Debugging techniques
Debugging with print
Debugging with a custom function
Inspecting the traceback
Using the Python debugger
Inspecting log files
Other techniques
Profiling
Assertions
Where to find information
Troubleshooting guidelines
Using console editors
Where to inspect
Using tests to debug
Monitoring
Summary
Installing the Required Software and Tools
Creating a virtual environment with Python 3.x and PEP 405
Understanding the directory structure for a virtual environment
Activating the virtual environment
Deactivating the virtual environment
Installing Django and Django REST frameworks in an isolated environment
Creating an app with Django
Understanding Django folders, files, and configurations
Installing tools
Installing Curl
Installing HTTPie
Installing the Postman REST client
Installing Stoplight
Installing iCurlHTTP
Test your knowledge
Summary
Working with Models, Migrations, Serialization, and Deserialization
Defining the requirements for our first RESTful Web Service
Creating our first model
Running our initial migration
Understanding migrations
Analyzing the database
Understanding the table generated by Django
Controlling, serialization, and deserialization
Working with the Django shell and diving deeply into serialization and deserialization
Test your knowledge
Summary
Creating API Views
Creating Django views combined with serializer classes
Understanding CRUD operations with Django views and the request methods
Routing URLs to Django views and functions
Launching Django's development server
Making HTTP GET requests that target a collection of instances
Making HTTP GET requests that target a single instance
Making HTTP POST requests
Making HTTP PUT requests
Making HTTP DELETE requests
Making HTTP GET requests with Postman
Making HTTP POST requests with Postman
Test your knowledge
Summary
Using Generalized Behavior from the APIView Class
Taking advantage of model serializers
Understanding accepted and returned content types
Making unsupported HTTP OPTIONS requests with command-line tools
Understanding decorators that work as wrappers
Using decorators to enable different parsers and renderers
Taking advantage of content negotiation classes
Making supported HTTP OPTIONS requests with command-line tools
Working with different content types
Sending HTTP requests with unsupported HTTP verbs
Test your knowledge
Summary
Understanding and Customizing the Browsable API Feature
Understanding the possibility of rendering text/HTML content
Using a web browser to work with our web service
Making HTTP GET requests with the browsable API
Making HTTP POST requests with the browsable API
Making HTTP PUT requests with the browsable API
Making HTTP OPTIONS requests with the browsable API
Making HTTP DELETE requests with the browsable API
Test your knowledge
Summary
Using Constraints, Filtering, Searching, Ordering, and Pagination
Browsing the API with resources and relationships
Defining unique constraints
Working with unique constraints
Understanding pagination
Configuring pagination classes
Making requests that paginate results
Working with customized pagination classes
Making requests that use customized paginated results
Configuring filter backend classes
Adding filtering, searching, and ordering
Working with different types of Django filters
Making requests that filter results
Composing requests that filter and order results
Making requests that perform starts with searches
Using the browsable API to test pagination, filtering, searching, and ordering
Test your knowledge
Summary
Securing the API with Authentication and Permissions
Understanding authentication and permissions in Django, the Django REST framework, and RESTful Web Services
Learning about the authentication classes
Including security and permissions-related data to models
Working with object-level permissions via customized permission classes
Saving information about users that make requests
Setting permission policies
Creating the superuser for Django
Creating a user for Django
Making authenticated requests
Making authenticated HTTP PATCH requests with Postman
Browsing the secured API with the required authentication
Working with token-based authentication
Generating and using tokens
Test your knowledge
Summary
Applying Throttling Rules and Versioning Management
Understanding the importance of throttling rules
Learning the purpose of the different throttling classes in the Django REST framework
Configuring throttling policies in the Django REST framework
Running tests to check that throttling policies work as expected
Understanding versioning classes
Configuring a versioning scheme
Running tests to check that versioning works as expected
Test your knowledge
Summary
Automating Tests
Getting ready for unit testing with pytest
Writing unit tests for a RESTful Web Service
Discovering and running unit tests with pytest
Writing new unit tests to improve the tests' code coverage
Running unit tests again with pytest
Test your knowledge
Summary
Solutions
Chapter 11: Installing the Required Software and Tools
Chapter 12: Working with Models, Migrations, Serialization, and Deserialization
Chapter 13: Creating API Views
Chapter 14: Using Generalized Behavior from the APIView Class
Chapter 15: Understanding and Customizing the Browsable API Feature
Chapter 16: Using Constraints, Filtering, Searching, Ordering, and Pagination
Chapter 17: Securing the API with Authentication and Permissions
Chapter 18: Applying Throttling Rules and Versioning Management
Chapter 19: Automating Tests
Templates
Understanding Django's template language features
Variables
Attributes
Filters
Tags
Philosophy – don't invent a programming language
Jinja2
Organizing templates
How templates work
Using Bootstrap
But they all look the same!
Lightweight alternatives
Template patterns
Pattern — template inheritance tree
Problem details
Solution details
Pattern — the active link
Problem details
Solution details
A template-only solution
Custom tags
Summary
Admin Interface
Using the admin interface
Enhancing models for the admin
Not everyone should be an admin
Admin interface customizations
Changing the heading
Changing the base and stylesheets
Adding a rich-text editor for WYSIWYG editing
Bootstrap-themed admin
Complete overhauls
Protecting the admin
Pattern – feature flags
Problem details
Solution details
Summary
Forms
How forms work
Forms in Django
Why does data need cleaning?
Displaying forms
Time to be crisp
Understanding CSRF
Form processing with class-based views
Form patterns
Pattern – dynamic form generation
Problem details
Solution details
Pattern – user-based forms
Problem details
Solution details
Pattern – multiple form actions per view
Problem details
Solution details
Separate views for separate actions
Same view for separate actions
Pattern – CRUD views
Problem details
Solution details
Summary
Security
Cross-site scripting
Why are your cookies valuable?
How Django helps
Where Django might not help
Cross-site request forgery
How Django helps
Where Django might not help
SQL injection
How Django helps
Where Django might not help
Clickjacking
How Django helps
Shell injection
How Django helps
And the web attacks are unending
A handy security checklist
Summary
Working Asynchronously
Why asynchronous?
Pitfalls of asynchronous code
Asynchronous patterns
Endpoint callback pattern
Publish-subscribe pattern
Polling pattern
Asynchronous solutions for Django
Working with Celery
How Celery works
Celery best practices
Handling failure
Idempotent tasks
Avoid writing to shared or global state
Database updates without race conditions
Avoid passing complex objects to tasks
Understanding asyncio
asyncio versus threads
The classic web-scraper example
Synchronous web-scraping
Asynchronous web-scraping
Concurrency is not parallelism
Entering Channels
Listening to notifications with WebSockets
Differences from Celery
Summary
Creating APIs
RESTful API
API design
Versioning
Django Rest framework
Improving the Public Posts API
Hiding the IDs
API patterns
Pattern – human browsable interface
Problem details
Solution details
Pattern – Infinite Scrolling
Problem details
Solution details
Summary
Production-Ready
The production environment
Choosing a web stack
Components of a stack
Virtual machines or Docker
Microservices
Hosting
Platform as a service
Virtual private servers
Serverless
Other hosting approaches
Deployment tools
Fabric
Typical deployment steps
Configuration management
Monitoring
Improving Performance
Frontend performance
Backend performance
Templates
Database
Caching
Cached session backend
Caching frameworks
Caching patterns
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
买过这本书的人还买过
读了这本书的人还在读
同类图书排行榜