Preface

"What do you want to do when you graduate college?" asked a family friend. "I'm not sure. I really like building web applications," I said. "Maybe I can do that." The response: "No, there's no future in that. Pick something else." Wow, was he wrong!

That was a conversation I had about 20 years ago. It was truly a demoralizing comment. I had begun experimenting with the web and programming in high school in the late 90s. However, burdened with this defeat, I naively accepted it as truth and kept web development as a hobby. Ultimately, I went on to law school and launched a career as a lawyer. Don't get me wrong, I loved being a lawyer and I loved the work that I did. But my years as an attorney drove me back to software development, ultimately turning my hobby into a career. This quite unusual career path was made possible by the open source community. Through the help and guidance of the community at large, I taught myself the skills I would need to become a professional. It is now my turn to help others.

I share this story because it highlights something that I think is applicable not only to my life but also to web application development in general. This bad advice is a reminder that not all guidance is good, and that the best course of action is the one that fits my needs, not those of someone else. This book is devoted to that concept.

To become better at what we do, we must constantly be moving forward on our journey, learning new things and polishing existing skills. We must take the advice, the design patterns, and the code snippets that others provide us and internalize them. Some of it will be good, and some of it will be bad. By knowing this, we can carefully select the good to build something that meets our challenges and is truly extraordinary.

Shortly, we will start a journey together learning about web development. By the end of this book, I hope that you feel empowered to build what you want and need, and not be constrained by bad advice. And maybe—just maybe—you might walk away with just a little more passion and respect for Sanic, for Python, and for open source software. I truly wish you the best of luck on your own personal journey.

Who this book is for

This book is for Python web developers who have basic- to intermediate-level 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 Python web development with frameworks such as Django and/or Flask may be helpful, but is not 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 helpful.

What this book covers

Chapter 1, Introduction to Sanic and Async Frameworks, covers the background information on why Sanic was built, how it is developed, where it is headed, and who should use it. Important takeaways include the difference between WSGI, Async, and ASGI servers; what is a framework versus a server; and what developers should do to set up their project for success.

Chapter 2, Organizing a Project, takes you through the common approaches to organizing a project, and ideas to help decide an appropriate solution that fits the needs of what you are building.

Chapter 3, Routing and Intaking HTTP Requests, focuses upon the first interactions that the server has with an incoming web request. You'll learn about: how requests are structured; what choices Sanic makes for us and what choices it leaves to us; and other issues involved in turning an HTTP request into actionable code.

Chapter 4, Ingesting HTTP Data, focuses on the types of data that can be received and some effective tools for handling them. You will learn how to extract (and use) data from headers, cookies, paths, body, and query arguments; and also some useful tools to make it easier to build good applications with the data.

Chapter 5, Building Response Handlers, explores different techniques for sending content back to the clients. Modern applications often need several techniques to provide high-quality experiences and dynamic content. You will learn about when to apply each technique and how to optimize Sanic for each use case.

Chapter 6, Operating Outside the Response Handler, goes through all of the other stuff that Sanic can do besides just simple response handlers. You will learn about how to use listeners, middleware, signals, and background tasks to customize web applications. The goal is to learn to recognize patterns that can be applied in a variety of use cases.

Chapter 7, Dealing with Security Concerns, focuses upon common security concerns and how to deal with them in Sanic. Since this topic alone is quite extensive, the approach will be to introduce the concern and explain the issue as it relates to Sanic. Then we will look at common mitigation strategies and what they would look like in Sanic.

Chapter 8, Running a Sanic Server, focuses upon setting up a server for both local development and production-ready environments. Again, this topic can be extremely lengthy by itself. Therefore, the goal is not to be a tutorial on how to use tools such as Docker and Kubernetes. After the introduction, this chapter assumes some working knowledge, provides other materials for reference, and focuses on what these tools mean for Sanic. You will learn about some common deployment patterns and when/how you should decide to use them.

Chapter 9, Best Practices to Improve Your Web Applications, covers some practical tips on how to make your web applications better. The areas covered are the sorts of finishing touches that make an application feel "professional," and most importantly easier to maintain for future iterations.

Chapter 10, Implementing Common Use Cases with Sanic, analyzes common to slightly advanced use cases in depth and how to implement them in Sanic. We will start each section with a description of the problems encountered. After providing solutions, we will do a review of the implementations and try to draw some conclusions and generalizations that can be taken by you to other applications.

Chapter 11, A Complete Real-World Example, provides you with a complete web application that you can learn from. The source code is available for you to review, and the application itself is hosted online so that you can interact with it while trying to learn from it. You are encouraged to check it out at https://sanicbook.com.

To get the most out of this book

The code examples in this book assume that you are running the latest long-term support (LTS) release. As of the time of writing, that is Sanic v21.12. We assume that you have a modern installation of Python available. While most of the examples will work fine in Python 3.7, to be able to run all of the code, you will need at least Python 3.8.

You are highly encouraged to follow along and run the code examples in this book. In addition, there are additional patterns and snippets that will only be available in the GitHub repository (see the next section for the link). You are highly encouraged to review these as well.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book's GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

The project is fast-moving and adopts new patterns all the time. Where possible, the GitHub repo will be kept up to date. If you encounter any problems while following the examples, you are encouraged to seek help at https://sanic.dev/help.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Python-Web-Development-with-Sanic. If there's an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781801814416_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "When an exception is raised, Sanic stops the regular route handling process and moves it over to an ErrorHandler instance."

A block of code is set as follows:

@app.exception(PinkElephantError)

async def handle_pink_elephants(request: Request, exception: Exception):

    ...

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

@app.exception(PinkElephantError)

async def handle_pink_elephants(request: Request, exception: Exception):

    ...

Any command-line input or output is written as follows:

$ pip install sanic-testing pytest

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: "Log in to the web portal, click on Kubernetes on the main dashboard, and set up a cluster."

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

Sanic help: If you run into any problems with your web applications or have questions about Sanic, you should turn to https://sanic.dev/help.

Author: To get in touch with the author, please contact him via Twitter @admhpkns or visit his web page at https://amhopkins.com.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you've read Python Web Development with Sanic, we'd love to hear your thoughts! Scan the QR code below to go straight to the Amazon review page for this book and share your feedback.

https://packt.link/r/1801814414

Your review is important to us and the tech community and will help us make sure we're delivering excellent quality content.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.186.92