Book Image

Python Web Development with Sanic

By : Adam Hopkins
Book Image

Python Web Development with Sanic

By: Adam Hopkins

Overview of this book

Today’s developers need something more powerful and customizable when it comes to web app development. They require effective tools to build something unique to meet their specific needs, and not simply glue a bunch of things together built by others. This is where Sanic comes into the picture. Built to be unopinionated and scalable, Sanic is a next-generation Python framework and server tuned for high performance. This Sanic guide starts by helping you understand Sanic’s purpose, significance, and use cases. You’ll learn how to spot different issues when building web applications, and how to choose, create, and adapt the right solution to meet your requirements. As you progress, you’ll understand how to use listeners, middleware, and background tasks to customize your application. The book will also take you through real-world examples, so you will walk away with practical knowledge and not just code snippets. By the end of this web development book, you’ll have gained the knowledge you need to design, build, and deploy high-performance, scalable, and maintainable web applications with the Sanic framework.
Table of Contents (16 chapters)
1
Part 1:Getting Started with Sanic
4
Part 2:Hands-On Sanic
11
Part 3:Putting It All together

Leveling up

Sanic encourages experimentation, customization, and, most of all, curiosity.

It is probably not the best tool for Python beginners since it assumes that they have some knowledge of both Python and web development. That is not to say that the project discourages newcomers, or people just getting into web development. Indeed, Sanic is a wonderful place to start learning about web development for those that truly want to understand the practice. Much of web development is learning to balance competing decisions. Sanic development often includes learning about these decision points.

This touches upon the goal of this book: answering the question, "what is the obvious path to building my Sanic application?" This book intends to explore different patterns that could be used in Sanic. While we will learn about the concepts that relate to Sanic, the principles can be abstracted and applied to building an application with any other framework or language. It is critical to remember that there is no "right" or "wrong" way. Online forums are filled with "what is the right way?" questions that assume that there is standard practice. The answers to these questions point to the implication that if they are not following a particular pattern, then their application is wrong.

For example, someone may ask the following questions:

  • What is the right way to serve internationalized content?
  • What is the right way to deploy my web app?
  • What is the right way to handle long-running operations?

These "right way" questions suffer from a critical flaw: the belief that there is only a single obvious solution. Structuring a question like this is the domain of opinionated frameworks that do not teach developers to think on their own. Ask these same questions on the Sanic forums, and you'll probably receive an "it depends" as your answer. Opinionated frameworks hinder creativity and design. They ultimately drive the developer into making choices based upon the constraints provided by the framework and not the constraints of the application's needs.

Instead, Sanic provides a set of tools to help developers craft the solutions that work for their use cases without mandating certain practices. This is why the built-in features of Sanic focus on functionality and the request/response cycle, and not on implementation details such as validation, cross-origin resource sharing (CORS), CSRF, and database management. All of that other stuff is, of course, important, and we will explore this in later chapters. But this book intends to look at the issues and see how you might solve the problem. Web applications and web APIs have differing needs, so you, as a developer, should be allowed to make the choices that are best suited (and obvious) to solving your problems.

Revisiting the previous questions, a better way to phrase them would be as follows:

  • How can I serve internationalized content?
  • Which deployment strategy will work for me, considering my constraints?
  • What are the trade-offs to consider for handling long-running operations?

By the end of this book, you will be able to spot these questions and use your creativity to come up with appropriate solutions. You will learn about some of the powerful strategies that Sanic has to offer. But by no means think that any given solution is the only way to do something. Just because it is outlined here does not mean that it is the right way, or that the tools being used only apply to one particular situation.

The right way is to use the tools that Sanic and Python provide to solve your problems. If you were tasked with making soup, you would find that there is no single way to do it. You could look up some recipes and try to learn some basic patterns: boil water, add ingredients, and so on. Ultimately, to master the art of soup-making, you need to cook within the constraints of your kitchen, equipment, ingredients, and the people you are serving. This is what I want you to learn about web development: master your tools, environment, and requirements to build what you need for your specific users.

While reading this book, you should both be learning and analyzing the patterns and code. Try to generalize the concepts and think about how to use similar ideas down the road in your code. We encourage you to read this book in its entirety or duck in and out of chapters if they apply to you. Both are valid approaches.

Let's take a closer look at the question about internationalization to see how framing the question differently impacts our application and our knowledge:

  • BAD: What is the right way to serve internationalized content?
  • GOOD: How can I serve internationalized content?

The answer to the first question would likely include a snippet of code from someone who has had this problem in the past. The developer would copy/paste and move on, not learning anything in the process (and therefore will be unable to generalize and apply knowledge to similar problems in the future). At best, the solution is passably acceptable. At worst, the solution is harmful to the overall design of the application and the developer doesn't even know it.

Framing the question as "How can I…" leaves open the idea that there may be multiple avenues to the same destination. The bad question style is narrow and drives our attention to a single approach. The good style opens up the possibilities to explore different solutions and weigh them against their merits. After asking the question, our job now is to figure out those possible solutions, determine the potential trade-offs, and then come to a conclusion. In this process, we can draw upon our own past experiences, examples from other developers, and resource materials such as this book.

We may think about possible solutions involving the following:

  • Middleware (catch the headers or path and reroute the request to a different handler)
  • Routing (embed the language code in the URL path and extract the language from the route)
  • Functional programming (use different functional handlers to generate separate responses)
  • Decorators (execute some logic before [or after] the actual handler is run)

But which solution should be used? We need to know about the specifics of our application. Here are some important questions to keep in mind:

  • Who is developing it? What is their experience level? How many developers are on the team? What tools will they be working with? Who will be maintaining it?
  • Who will be using the application? Will it be consumed from a frontend JavaScript (JS) framework? A mobile app? Third-party integrations?
  • How big will it scale? What sort of content needs to be delivered?

These questions are the domain of this book. We intend to ask these questions and determine the reasons behind making particular design pattern decisions. Of course, we cannot be exhaustive. Instead, we hope to inspire your journey to use as many tools and creative solutions as you can.

Few projects can match the amount of literature that has been written about Django. But precisely because Sanic does not require specific patterns, there is no need for such expansive amounts of documentation. The only prerequisite is knowing Python. The depth of API-specific knowledge that's needed to be successful with Sanic is not large. Do you know how to instantiate objects, pass values, and access properties? Of course, you do—it's just Python!

Two obvious valuable Sanic-specific resources are the User Guide (https://sanic.dev) and the API documentation (https://sanic.readthedocs.io). We will refer to both of these heavily in this book. But equally important is any other source on the web or in print that you have used up to this point to learn Python.

Coming back to the question of the obvious way to handle some tasks within Sanic: use the resources and tools that exist. There is a wealth of information on StackOverflow and the Sanic Community Forums. The Discord server is an active live discussion channel. Make yourself known, make your voice heard.

Don't ask the right way questions. Instead, ask the how can I questions. Next, we will learn a little bit about where Sanic falls in the web ecosystem, and its unusual place as both a framework and server.