Python Web Development with Sanic: An in-depth guide for Python web developers to improve the speed and scalability of web applications
- Length: 355 pages
- Edition: 1
- Language: English
- Publisher: Packt Publishing
- Publication Date: 2022-04-11
- ISBN-10: 1801814414
- ISBN-13: 9781801814416
- Sales Rank: #0 (See Top 100 Books)
Follow along with author Adam Hopkins and build a performant and scalable web application using Sanic, along with maintaining clean code to fit your unique challenges and business requirements
Key Features
- Use the power of Sanic to build a scalable and high-performant web application
- Analyze and implement Sanic in common use cases
- Create a complete web application from scratch using the latest features of the Sanic framework
Book Description
Today’s developers need something more powerful and customizable when it comes to web app development. They want the tools to build something, and not simply glue a bunch of things together built by others. This is where Sanic comes into the picture. It’s a next-generation Python framework and server tuned for high performance and built to be unopinionated and scalable.
You’ll start by understanding Sanic’s purpose, significance, and use cases. Next, you’ll learn to spot different issues when building web applications, and how to choose, create, and adapt the right solution to meet your needs. As you progress, you’ll understand how to use listeners, middleware, and background tasks to customize your application. The book will take you through real-world examples, so you walk away with practical knowledge and not just code snippets.
By the end of this web development book, you will have gained the knowledge you need to design, build, and deploy high-performance, scalable, and maintainable web applications with the Sanic framework.
What you will learn
- Strengthen your knowledge of web application architecture
- Explore the difference between WSGI, Async, and ASGI servers
- Understand the core philosophies of performance, scalability, and unopinionated
- Focus on how Sanic organizes incoming data, why it does it, and how to make the most of it
- Implement best practices for reliable, performant, and secure web apps
- Understand useful techniques for successfully deploying a Sanic web app
- Create an effective custom task manager within Sanic
- Discover security concerns and how to deal with them in your Sanic apps
Who This Book Is For
This book is for Python web developers who have knowledge of how web technologies work and are looking to enhance their skills by taking their applications to the next level using the power of the Sanic framework. Working knowledge of Django and/or Flask is required. A basic to intermediate-level understanding of Python 3, HTTP, RESTful API patterns, and modern development practices and tools, such as type annotations, pytest, and virtual environments is also assumed.
Table of Contents
- An Introduction to Sanic and Async Frameworks
- Organizing a Project
- Routing and Intaking HTTP Requests
- Ingesting HTTP Data
- Handling and Responding Views
- Outside the Response Cycle
- Dealing with Security Concerns
- Running a Server
- Best Practices to Improve Your Web Applications
- Implementing Sanic in Common Use Cases
- A Complete Real-World Example
B17504_10 Python Web Development with Sanic Python Web Development with Sanic 1 Introduction to Sanic and async frameworks Technical requirements What is Sanic? Leveling up Framework v server Web server Web framework Why we use Sanic—Build fast. Run fast. Simple and lightweight Unopinionated and flexible Performant and scalable Production ready Trusted by millions Community driven What drives code decisions? Summary 2 Organizing a project Technical requirements Setting up an environment and directory Environment Sanic CLI Directory Structure Using Blueprints effectively Blueprint registration Blueprint versioning Grouping blueprints Wiring it all up Controlled imports Factory pattern Autodiscovery Running our application Summary 3 Routing and Intaking HTTP Requests Technical requirements Understanding HTTP Methods Using HTTP Methods on route handlers Advanced method routing Method safety and request body RESTful API design Simplifying your endpoints with Class-Based Views Blanket support for OPTIONS and HEAD Paths, slashes, and why they matter Strict slashes Extracting information from the path Advanced path parameters Custom parameter matching Modifying matched parameter values API versioning Should all of my routes bump versions? Version prefixing Virtual hosts Serving static content Serving static content from Sanic Serving static content with Nginx Streaming Static Content Summary 4 Ingesting HTTP Data Technical requirements Reading cookies and headers Headers are flexible Authentication headers Context headers Sanic extracts some header data for us Headers as multi-dict Getting information from cookies (yum!) Reading forms, query arguments, files, JSON, and more Query arguments Forms and files Consuming JSON data Getting streaming data Validating data Step one: getting started and making a decorator Step two: reading the handler signature Step three: modeling Step four: model hydration Step five: performing validations Taking it to the next level with third-party packages Summary 5 Handling and Responding Views Technical requirements Examining the HTTP response structure HTTP response status Response groupings Response through exceptions Custom status Headers Response Body Rendering HTML content Delivering HTML files Basic templating Using a templating engine Serializing JSON content Choosing on a serializer Serializing custom objects Best practices Streaming data File streaming Server-Sent Events for push communication Starting with the basics Building some SSE objects Websockets for two-way communication Setting Response Headers and Cookies Responding with a request ID Setting response cookies Summary 6 Operating outside the Request Handler Technical requirements Making use of ctx Altering requests and responses with middleware Request middleware Response middleware Responding early (or late) with middleware Middleware and streaming responses Leveraging signals for intra-worker communication Signal definitions Using built-in signals Custom signals Waiting on events Mastering HTTP connections Keep-Alive within Sanic Caching data per connection Handling exceptions like a pro Implementing proper Exception handling Bad exception messages Misusing statuses Responses through raising an exception Fallback handling Catching exceptions Background processing Adding tasks to the loop Integrating with an outside service Designing an in-process task queue Summary 7 Dealing with Security Concerns Technical requirements Setting up an effective CORS policy What is the security issue with ineffective CORS? Protecting applications from CSRF Solutions that do not work Solutions that do work Samesite cookies Protecting your Sanic app with authentication Using API Keys Understanding session versus non-session based authentication Using sessions JWT (JSON Web Token) Summary 8 Running a Sanic Server Technical requirements Handling the server lifecycle Server listeners Configuring an application Running Sanic locally How does running Sanic locally differ from production? Deploying to production Choosing the right server option How to choose a deployment strategy? Securing your application with TLS Setting up TLS in Sanic Getting and renewing a certificate from Let’s Encrypt Deployment examples Platform-as-a-service Kubernetes (as-a-service) Summary 9 Best Practices to Improve your Web Applications Technical requirements Implementing practical real-world exception handlers Catching errors with middleware Catching errors with signals Catching the error and responding manually Modifying the ErrorHandler Setting up a testable application Getting started with sanic-testing A more practical test client implementation Using the ReusableClient for testing Gaining insight from logging and tracing Types of Sanic loggers Creating your own loggers, my first step in application development Configuring logging Adding color context Adding some basic tracing with request IDs Using X-Request-ID Managing database connections To ORM or Not to ORM, that is the question Creating a custom data access layer in Sanic Connecting Sanic to Redis Summary 10 Implementing Common Use Cases with Sanic Technical requirements Websocket feeds Powering a progressive web app Dealing with subdomains and CORS Running a development server GraphQL Why would I want to use GraphQL? Adding GraphQL to Sanic Building a Discord bot (running Sanic in another service) Building a simple discord bot Running the Discord bot from Sanic Nested Sanic applications: running Sanic inside Sanic to create a HTTP proxy Summary
Donate to keep this site alive
How to download source code?
1. Go to: https://github.com/PacktPublishing
2. In the Find a repository… box, search the book title: Python Web Development with Sanic: An in-depth guide for Python web developers to improve the speed and scalability of web applications
, sometime you may not get the results, please search the main title.
3. Click the book title in the search results.
3. Click Code to download.
1. Disable the AdBlock plugin. Otherwise, you may not get any links.
2. Solve the CAPTCHA.
3. Click download link.
4. Lead to download server to download.