Introduction¶
Sanic is a micro web framework that is designed to be fast and easy to use. It is both a framework and a web server. Sanic comes with everything that you need to write, deploy, and scale a production grade web application.
Getting Started¶
To teach you the basics of working with Sanic, we are going to build a simple web application that greets the world. Copy the following into a file called server.py
.
Simple Web App
It is important to note that the request
object is always the first argument of your handler. Also, you are always required to state the response type. This is done at the expense of ease for the benefit of a faster reponse.
Now to run the server, we simply run the following command:
The output that you get will look something like this:
[2022-05-27 09:39:13 -0400] [15506] [INFO]
┌─────────────────────────────────────────────────────────────────┐
│ Sanic v22.3.2 │
│ Goin' Fast @ http://0.0.0.0:8000 │
├───────────────────────┬─────────────────────────────────────────┤
│ │ mode: debug, single worker │
│ ▄███ █████ ██ │ server: sanic │
│ ██ │ python: 3.9.12 │
│ ▀███████ ███▄ │ platform: macOS-10.16-x86_64-i386-64bit │
│ ██ │ packages: sanic-routing==22.3.0 │
│ ████ ████████▀ │ │
│ │ │
│ Build Fast. Run Fast. │ │
└───────────────────────┴─────────────────────────────────────────┘
[2022-05-27 09:39:13 -0400] [15506] [DEBUG] Dispatching signal: server.init.before
[2022-05-27 09:39:13 -0400] [15506] [DEBUG] Dispatching signal: server.init.after
[2022-05-27 09:39:13 -0400] [15506] [INFO] Starting worker [15506]
Our server is now open at http://localhost:8000/, to view it we can eith use curl or open the browser and navigate there to see the output.