Coding With Fun
Home Docker Django Node.js Articles FAQ

Python's fastest Web framework

May 28, 2021 Article blog

Table of contents

If you're going to use Python for web development, I think you're going to tell me to use Flask or Django or tornado to use all three frameworks. M aybe a friend who goes around github will also say a fastapi. B ut, Emperor, times have changed, Daqing... He's dead!!!

Speed first

At the moment, python has been updated to Python 3.9.3, if you haven't used the new asyncio, and Python 3.5 new async/await syntax, that means you may really be a peach blossom source, ask what it is now, I don't know han, no matter Wei Jin.

At the moment, there are a lot of asynchronous Web frameworks based on async/await syntax, so which one should be chosen? There's a project on github that specializes in testing web framework speeds in a variety of languages, so let's take a look at simple data:

This is all Python Web Framework Speed Tests, and one might ask why you didn't start sorting from 1, because this project also includes 226 Web frameworks in golang, java, php, and many other languages. Here we only use Python for comparison.

It's clear that established Python web frameworks such as flask, django, and tornado are on the verge of bottoming out.

Wow, this speed is amazing. Perhaps you are still wondering how this speed is tested, and show you the test source code:

# Disable all logging features
import logging


from flask import Flask
from meinheld import patch


app = Flask(__name__)

def index():
    return ""

@app.route("/user/<int:id>", methods=["GET"])
def user_info(id):
    return str(id)

@app.route("/user", methods=["POST"])
def user():
    return ""
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

def index(request):
    return HttpResponse(status=200)

def get_user(request, id):
    return HttpResponse(id)

def create_user(request):
    return HttpResponse(status=200)
# Disable all logging features
import logging


import tornado.httpserver
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):

class UserHandler(tornado.web.RequestHandler):
    def post(self):

class UserInfoHandler(tornado.web.RequestHandler):
    def get(self, id):

app = tornado.web.Application(
        (r"/", MainHandler),
        (r"/user", UserHandler),
        (r"/user/(\d+)", UserInfoHandler),
# Disable all logging features
import logging


import multiprocessing

from sanic import Sanic
from sanic.response import text

app = Sanic("benchmark")

async def index(request):
    return text("")

@app.route("/user/<id:int>", methods=["GET"])
async def user_info(request, id):
    return text(str(id))

@app.route("/user", methods=["POST"])
async def user(request):
    return text("")

if __name__ == "__main__":
    workers = multiprocessing.cpu_count()"", port=3000, workers=workers, debug=False, access_log=False)

Is simply do nothing, only return response, although such testing has no practical meaning, in the normal production environment can not do nothing, but if all the frameworks are tested like this, it is from a certain extent on the same starting line.

OK, that's all, and you should know who this asynchronous framework I'm trying to say is, yes, our main character today is Sanic.

 Python's fastest Web framework1

Why use an asynchronous web framework?

Is this probably the first thing many little partners think of? I use Django, Flask, good, able to do normal tasks, why use asynchronous web framework?

 Python's fastest Web framework2

Having said that, first of all, I'm going to ask you a question, who do you think is our worst enemy in web development? Think for 5 seconds and see my answer:

In web development, our worst enemy is not users, but blocking!

Yes, and asynchronous can effectively solve network I/O blocking, file I/O blocking. S pecific blocking-related articles recommend looking at an in-depth understanding of Python asynchronous programming. B ecause asynchronous increases efficiency, asynchronous is one of the best ways for Python to improve performance. That's why you chose an asynchronous Web framework.

Ecological environment

May have a small partner or will say, why don't you recommend falcon instead of Sanic? Clearly it's very fast, so much faster than Sanic, so take a look at the following code:

from wsgiref.simple_server import make_server
import falcon

class ThingsResource:
    def on_get(self, req, resp):
        """Handles GET requests"""
        resp.status = falcon.HTTP_200  # This is the default status
        resp.content_type = falcon.MEDIA_TEXT  # Default is JSON, so override
        resp.text = ('\nTwo things awe me most, the starry sky '
                     'above me and the moral law within me.\n'
                     '    ~ Immanuel Kant\n\n')

app = falcon.App()

things = ThingsResource()

app.add_route('/things', things)

if __name__ == '__main__':
    with make_server('', 8000, app) as httpd:
        print('Serving on port 8000...')


A status code has to define and fill out its own framework, I think it is worth affirming the speed, but for developers, how much practical value? So we choose the framework not to choose the fastest, but to be fast and easy to use.

Most frameworks don't have such an ecosystem, which should be why most Python Web developers are willing to choose Django, Flask, and tornado. It is because their ecology is much richer than other frameworks.

But now it's different. The Sanic Framework, which has been releasing the first asynchronous web framework prototype since May 2016, has been in its fifth year, and over the past five years, Sanic has gone from a faltering small frame to a robust, steady frame.

In the awesome-sanic project, you've documented a large number of third-party libraries, and you can find any commonly used tool: from API to Viable, from Development to Frontend, from Monitoring to ORM, from Caching to Queue... Only you can't imagine, no third-party expansion without it.

Production environment

I've seen some small partners in the domestic community before asking, "Can Sanic be used in production environments in 2020?"

 Python's fastest Web framework3

The answer is yes, the author testified with personal experience that we have been using Sanic for production since the end of 19. At that time Sanic was still 19.9, and the author experienced all the sanic versions of Sanic 19.9 - 21.3, and watched Sanic's ecological environment become better and better.

Another problem you may not know is that Sanic's goal at the beginning was to create a Web framework that could be used in production environments. I t may be clear from some frameworks that the Run method that comes with the framework is for testing environments only, not for deployment environments. B ut Sanic creates more than just an application for a test environment, it can be used directly in a production environment. Eliminate the hassle of using deployments such as unicorn!

The documentation is well documented

Presumably the first framework that most Python Web developers learn is Flask or Django, especially Django's documentation, and I think most of my little friends will be distracted when they look at it. B ecause the old version has Chinese, but the new version, especially the new feature, has no Chinese documentation at all!!!! It's hard for students who are concerned about Django's development but are not strong in English.

However, Sanic has a comprehensive Chinese user guide and API documentation, which are initiated by contributors, officially recognized documents, translated contributions by translators, and published by Sanic's official team. S ome small partners may say that Flask also has well-Chinese documentation, but that's on different sites, and all of Sanic's documents are supported by Sanic's official release. Sanic continues to support more languages such as Korean and Portuguese.

 Python's fastest Web framework4

Community guidance

Unlike other frameworks, you may be able to find forums, channels, etc. on Baidu, but these are locally Chinese, often not official, and contain a lot of advertising. It is clear that this cannot be allowed to happen if it is officially operated.

Unlike other communities, Sanic's forums and channels are fully officially run, where you can ask questions of the core developers, and Sanic's official publishing manager is happy to answer questions. Y ou can also share your experiences with like-minded users. It's a completely open environment....

Sanic currently uses forums, Discords, githubs, twitter, Stackoverflow

 Python's fastest Web framework5

You can follow Sanic's development and seek community help in the way above.

 Python's fastest Web framework6

What are you waiting for? D on't you hurry to try it? Finally, end with Sanic's vision: Build Faster, Run Faster!

Reprinted from:

That's what's the difference between Java and equals that the little editor has compiled for you? t he whole content