Using Sanic as an asynchronous http server

Using Sanic as an asynchronous http server
Photo by Windows / Unsplash

If you are interested in learning to code your own http server in python. I recommend, dear reader a venture into using Sanic. Sanic is a performant asyncronous http server that uses uvloop, which is a replacement for the asyncio event loop which is atleast 2x as fast as nodejs.

While the server itself is fast, it is largely similar to flask which should make translating your knowledge from using flask to using sanic fairly easy. Of course all the usual considerations about writing a performant server apply – ie your server will likely be as fast as your database, caching layers and apis that you call in the backend.

The Demo Sanic Stack

I use a combination of sqlalchemy as a data backend for this example, where user information is stored in a sqlite database. User authentication is then performed and authorization is managed via using the sanic-jwt library which submits back a jwt encoded bearer token. This token provides basic encrypted information about the user that holds the token and provides the server with additional information about the privaleges the user holds. A request can then be sent to the server to a protected endpoint for users to interact with elevated permissions.

An example of this code is provided at the sanic-introduction repositroy hosted at github. If you have questions, problems, issues or comments. Feel free to leave a comment at the repository.