Introduction to Sanic Web Framework – Python
Last Updated :
10 May, 2022
WHAT IS SANIC? Sanic is an asynchronous web framework and web server for Python 3.5+ that’s written to go fast. Sanic was developed at MagicStack and is based on their uvloop event loop, which is a replacement for Python asyncio’s default event loop, thereby making Sanic blazing fast. Syntactically Sanic resembles Flask. Sanic maybe used as a replacement for Django or Flask to build highly scalable, efficient and blazing fast performant web applications. BUILDING OUR FIRST SANIC APP! Step 1: It is preferable to use virtual environments in Python to create isolated environments with project-specific dependencies. Since Sanic 19.6+ versions do not support Python 3.5, we will work with Python 3.6+. To install sanic in our Python virtual environment we will execute the following command – pip3 install sanic Step 2: Let us create a directory named sanic_demo & within it a file named main.py with the following lines of code –
Python3
from sanic import Sanic
from sanic import response
app = Sanic("My First Sanic App")
@app .route(" / ")
def run(request):
return response.text("Hello World !")
app.run(host = " 0.0 . 0.0 ", port = 8000 , debug = True )
|
Step 3: We may either run main.py from an IDE, or run the file from Terminal by executing the following command – python3 main.py The Sanic web server is up on 8000 port of our ‘localhost’.
Step 4: Navigating to http://0.0.0.0:8000/ from our web browser renders “Hello World!”.
CONFIGURATION The config attribute of the Sanic app object is used to configure parameters. The app config object can be assigned key-value pairs as follows :
Python3
from sanic import Sanic
from sanic import response
app = Sanic("My First Sanic App")
app.config["SECURITY_TOKEN"] = [{"ApiKeyAuth": []}]
|
The full list of configuration params is available at the official documentation page – Sanic Config ROUTING AND BLUEPRINTS Sanic supports the route decorator to map handler functions to HTTP requests. We can use an optional parameter called methods in the ‘route’ decorator to work with any of the HTTP methods in the list. Blueprints is a concept used for plugging sub-routes into the Sanic app from sub-modules of a large application. Blueprints must be registered into the Sanic app object. Using blueprints also avoids passing around the Sanic app object all over the application. Let us modify our original main.py file to demonstrate the usage of routes and blueprints –
Python3
from sanic import Sanic
from sanic import response
from sanic.log import logger
from controller import my_bp
app = Sanic("My First Sanic App")
app.blueprint(my_bp)
@app .route(" / ")
def run(request):
return response.text("Hello World !")
@app .route(" / post", methods = [ 'POST' ])
def on_post(request):
try :
return response.json({"content": request.json})
except Exception as ex:
import traceback
logger.error(f"{traceback.format_exc()}")
app.run(host = " 0.0 . 0.0 ", port = 8000 , debug = True )
|
Let us create a new file named controller.py to declare our blueprints –
Python3
from sanic import response
from sanic import Blueprint
my_bp = Blueprint( 'my_blueprint' )
@my_bp .route( '/my_bp' )
def my_bp_func(request):
return response.text( 'My First Blueprint' )
|
Let us run main.py and check the results when /my_bp endpoint is accessed –
We have used a web client called ‘Insomnia‘ to demonstrate our POST request –
RENDERING CONTENT Sanic routes can serve html files, json content, media files etc. To serve static content like images, pdf, static html files etc we need to use app.static() method which maps the path of a static file to an endpoint specified by a ‘route’. Let us modify our main.py file to demonstrate this –
Python3
from sanic import Sanic
from sanic import response
from sanic.log import logger
from controller import my_bp
app = Sanic("My First Sanic App")
app.blueprint(my_bp)
app.static( '/floral_image.jpg' ,
'/sanic_demo / ws_Beautiful_flowers_1920x1080.jpg' )
@app .route(" / ")
def run(request):
return response.text("Hello World !")
@app .route(" / post", methods = [ 'POST' ])
def on_post(request):
try :
return response.json({"content": request.json})
except Exception as ex:
import traceback
logger.error(f"{traceback.format_exc()}")
app.run(host = " 0.0 . 0.0 ", port = 8000 , debug = True )
|
Running main.py and accessing http://0.0.0.0:8000/floral_image.jpg renders the image on the browser.
Let us further modify main.py to access some html content – Let us create a sample index.html file –
html
< html >
<!DOCTYPE html>
< html lang="en">
< head >
< meta charset="UTF-8">
< title >Render HTML on Sanic</ title >
</ head >
< body >
Gotta go fast!
</ body >
</ html >
|
Python3
from sanic import Sanic
from sanic import response
from sanic.log import logger
from controller import my_bp
app = Sanic("My First Sanic App")
app.blueprint(my_bp)
app.static( '/floral_image.jpg' ,
'/sanic_demo / ws_Beautiful_flowers_1920x1080.jpg' )
@app .route(" / ")
def run(request):
return response.text("Hello World !")
@app .route(" / post", methods = [ 'POST' ])
def on_post(request):
try :
return response.json({"content": request.json})
except Exception as ex:
import traceback
logger.error(f"{traceback.format_exc()}")
@app .route(" / display")
def display(request):
return response. file ( '/sanic_demo / index.html' )
app.run(host = " 0.0 . 0.0 ", port = 8000 , debug = True )
|
Running main.py and accessing http://0.0.0.0:8000/display renders the following on the browser –
EXCEPTION HANDLING Exceptions can be explicitly raised within Sanic request handlers. The Exceptions take a message as the first argument and can also include a status code. The @app.exception decorator can be used to handle Sanic Exceptions. Let us demonstrate by tweaking our main.py file –
Python3
from sanic import Sanic
from sanic import response
from sanic.log import logger
from controller import my_bp
from sanic.exceptions import ServerError, NotFound
app = Sanic("My First Sanic App")
app.blueprint(my_bp)
app.static( '/floral_image.jpg' ,
'/sanic_demo / ws_Beautiful_flowers_1920x1080.jpg' )
@app .route( '/timeout' )
async def terminate(request):
raise ServerError("Gateway Timeout error", status_code = 504 )
@app .exception(NotFound)
async def ignore_5xx(request, exception):
return response.text(f"Gateway is always up: {request.url}")
@app .route(" / ")
def run(request):
return response.text("Hello World !")
@app .route(" / post", methods = [ 'POST' ])
def on_post(request):
try :
return response.json({"content": request.json})
except Exception as ex:
import traceback
logger.error(f"{traceback.format_exc()}")
@app .route(" / display")
def display(request):
return response. file ( '/sanic_demo / index.html' )
app.run(host = " 0.0 . 0.0 ", port = 8000 , debug = True )
|
Exception rendered on browser –
NotFound (thrown when request handler not found for route) and ServerError(thrown due to serve code issues) are most commonly used. ASYNC SUPPORT Web applications characteristically talk to external resources, like databases, queues, external APIs etc to retrieve information required to process requests. Sanic, a Python Web Framework that has Python 3.5+’s asyncio library’s async/await syntax pre-baked into it, is the ideal candidate for designing large scale I/O bound projects which work with many connections. This enables the webapp’s requests to be processed in a non-blocking and concurrent way. Python 3.5 introduced asyncio, which is a library to write concurrent code using the async/await syntax (source: https://docs.python.org/3/library/asyncio.html). The asyncio library provides an event loop which runs async I/O functions. Sanic provides support for async/await syntax, thereby making request handling non-blocking and super fast. Adding the async keyword to request handler functions makes the function handle the code asynchronously, thereby leveraging Sanic’s performance benefits. Instead of asyncio’s event loop, Sanic uses MagicStack’s proprietary uvloop which is faster than asyncio’s event loop, leading to blazing fast speeds. However, on Windows OS, Sanic reverts to asyncio’s event loop under the hood, due to issues with uvloop on Windows. Reference: Sanic Official Docs.
Similar Reads
Introduction to Bottle Web Framework - Python
There are many frameworks in python which allows you to create webpage like bottle, flask, django. In this article you will learn how to create simple app bottle.Bottle is a fast, simple and lightweight WSGI micro web-framework for Python. It is distributed as a single file module and has no depende
2 min read
Introduction to JustPy | A Web Framework based on Python
JustPy is a web framework that leverages the power of Python to create web applications effortlessly. In this article, we'll explore JustPy, its features, and why it's gaining attention among developers. What is the JustPy Module of Python?The JustPy module of Python is a web framework like Django b
8 min read
Introduction to Tornado Framework
Tornado is a robust Python asynchronous networking library and web framework, is available as an open-source project. Given that it is made to manage non-blocking, asynchronous processes, it is appropriate for developing high-performance, scalable web apps. Since its creation, Tornadoâwhich was firs
3 min read
Introduction to NiceGUI - A Python based UI framework
In this article, we will learn about NiceGUI, It is a Python-based UI Framework, which shows up in Web Browsers and we can create buttons, dialogs, Markdown, 3D scenes, plots, and much more. It works well for dashboards, robotics initiatives, smart house solutions, and other related use cases. Addit
5 min read
Python Falcon Introduction
Python Falcon is a lightweight, high-performance web framework that's well-suited for building RESTful APIs. It's easy to learn, efficient, and perfect for projects where speed and simplicity are priorities. In this article, we introduced Falcon and created a basic "Hello World" application to help
4 min read
Introduction to Python for Absolute Beginners
Are you a beginner planning to start your career in the competitive world of Programming? Looking resources for Python as an Absolute Beginner? You are at the perfect place. This Python for Beginners page revolves around Step by Step tutorial for learning Python Programming language from very basics
6 min read
Introduction to Web development using Flask
Flask is a lightweight and flexible web framework for Python. It's designed to make getting started with web development quick and easy, while still being powerful enough to build complex web applications. It is an API of Python that allows us to build web applications. It was developed by Armin Ron
11 min read
Web Driver Methods in Selenium Python
Seleniumâs Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout â Navigating links using get method â Selenium Python. Just bein
5 min read
Python Script to Open a Web Browser
In this article we will be discussing some of the methods that can be used to open a web browser (of our choice) and visit the URL we specified, using python scripts. In the Python package, we have a module named webbrowser, which includes a lot of methods that we can use to open the required URL in
4 min read
Selenium Python Introduction and Installation
Selenium's Python Module is built to perform automated testing with Python. Selenium in Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. Through Selenium Python API you can access all functionalities of python selenium webdriver intuitively. Table
4 min read