Is Sanic python web framework the new Flask?

Intro

The Facts

The Pros

Perfromance comparision between Flask and Sanic

The Cons

Lets create a simple app using Sanic

from sanic import Sanic
from sanic.response import json

app = Sanic(__name__)
@app.route("/")
async def test(request):
return json({"message": "Hello_world"})

if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)

from sanic import Sanic
from sanic import response
from sanic.response import json

app = Sanic(__name__)


@app.route("/", methods=["GET"])
async def index(request):
return json({"message": "Hello_world"})


@app.route("/post", methods=["POST"])
async def post(request):
return json({"message": request.json})


@app.route("/empty", methods=["PUT"])
async def empty_response(request):
return response.empty()


if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
from json import loads, dumps
from humps import camelize, decamelize


class Camelize:
def __init__(self, app):
@app.middleware("request")
async def request_to_snake_case(request):

if request.body:
request.body = bytes(dumps(decamelize(loads(request.body))), "utf-8")

@app.middleware("response")
async def response_to_camel(request, response):

if response.body:
response.body = bytes(dumps(camelize(loads(response.body))), "utf-8")
# -*- coding: utf-8 -*-
"""Sample main.py used for running tests for middleware

"""
from sanic import Sanic
from sanic import response
from sanic.response import json
from sanic_camelcase_middleware import Camelize

app = Sanic(__name__)

Camelize(app)


@app.route("/", methods=["GET"])
async def index(request):
return json({"is_camelcase": True, "message": "Hello_world"})


@app.route("/post", methods=["POST"])
async def post(request):
return json({"is_camelcase": True, "message": request.json})


@app.route("/empty", methods=["PUT"])
async def empty_response(request):
return response.empty()


if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
{"isCamelcase": true, "message": "Hello_world"}

Writing tests

import json
from humps import camelize
from main import app

def test_get_request():
"""test_get_request function tests get requests for middleware
The purpose of this test is to check if the middleware would work if the request
has no payload in case of "GET" requests.
However the respons should be camilized.
"""
request, response = app.test_client.get("/")
assert response.status == 200
assert response.json == {"isCamelcase": True, "message": "Hello_world"}

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store