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

Altering requests and responses with middleware

If you have been following along with the book up until now, the concept of middleware should be familiar. This is the first tool in the tool belt that you should become familiar with.

Middleware is snippets of code that can be run before and after route handlers. Middleware comes in two varieties: request and response.

Request middleware

The request middleware executes in the order in which it was declared, before the route handler, as shown here:

@app.on_request
async def one(request):
    print("one")
@app.on_request
async def two(request):
    print("two")
@app.get("/")
async def handler(request):
    print("three")
    return text("done")

When we try to reach this endpoint, we should see the following in the Terminal:

one
two
three
(sanic.access)[INFO][127.0.0.1:47194]: GET http://localhost...