0%

Book Description

A comprehensive guide to Python programming for web development using the most popular Python web framework - Django

Key Features

  • Learn the fundamentals of programming with Python and building web apps
  • Build web applications from scratch with Django
  • Create real-world RESTful web services with the latest Django framework

Book Description

If you want to develop complete Python web apps with Django, this Learning Path is for you. It will walk you through Python programming techniques and guide you in implementing them when creating 4 professional Django projects, teaching you how to solve common problems and develop RESTful web services with Django and Python. You will learn how to build a blog application, a social image bookmarking website, an online shop, and an e-learning platform.

Learn Web Development with Python will get you started with Python programming techniques, show you how to enhance your applications with AJAX, create RESTful APIs, and set up a production environment for your Django projects. Last but not least, you'll learn the best practices for creating real-world applications.

By the end of this Learning Path, you will have a full understanding of how Django works and how to use it to build web applications from scratch.

This Learning Path includes content from the following Packt products:

? Learn Python Programming by Fabrizio Romano

? Django RESTful Web Services by Gaston C. Hillar

? Django Design Patterns and Best Practices by Arun Ravindran

What you will learn

  • Explore the fundamentals of Python programming with interactive projects
  • Grasp essential coding concepts along with the basics of data structures and control flow
  • Develop RESTful APIs from scratch with Django and the Django REST Framework
  • Create automated tests for RESTful web services
  • Debug, test, and profile RESTful web services with Django and the Django REST Framework
  • Use Django with other technologies such as Redis and Celery

Who this book is for

If you have little experience in coding or Python and want to learn how to build full-fledged web apps, this Learning Path is for you. No prior experience with RESTful web services, Python, or Django is required, but basic Python programming experience is needed to understand the concepts covered.

Table of Contents

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