If you want to use Python for web development, I think you will tell me to use Flask or Django or tornado, which is nothing more than these three frameworks. Maybe friends who visit github more will say a fastapi. However, emperor, the times have changed, the Qing Dynasty... Died!!!
Speed first
At present, python has been updated to Python 3 9.3, if you haven't used asyncio, and python 3 5. The new async/await grammar shows that you may really be from Taohuayuan. Ask what age it is. I don't know whether there is a Han Dynasty, regardless of the Wei and Jin Dynasties.
At present, there are many asynchronous Web frameworks based on async/await syntax. You can find them everywhere on github. Which one should you choose? There is a project dedicated to testing the speed of various Web frameworks in various languages on github. Let's take a look at the simple data:
This is the speed test of all Python Web frameworks. Someone may ask why it is not sorted from 1, because the test of this project also includes Web frameworks in many languages such as golang, java and php, with a total of 226 models. Here we only use Python for comparison.
It is obvious that the old Python Web frameworks such as flash, django and tornado are almost at the bottom.
wow, this speed is amazing. Maybe you are still wondering how to test the speed. Let me show you the test source code:
# Disable all logging features import logging logging.disable() from flask import Flask from meinheld import patch patch.patch_all() app = Flask(__name__) @app.route("/") 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) @csrf_exempt def create_user(request): return HttpResponse(status=200) Copy code # Disable all logging features import logging logging.disable() import tornado.httpserver import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): pass class UserHandler(tornado.web.RequestHandler): def post(self): pass class UserInfoHandler(tornado.web.RequestHandler): def get(self, id): self.write(id) app = tornado.web.Application( handlers=[ (r"/", MainHandler), (r"/user", UserHandler), (r"/user/(\d+)", UserInfoHandler), ] ) Copy code # Disable all logging features import logging logging.disable() import multiprocessing from sanic import Sanic from sanic.response import text app = Sanic("benchmark") @app.route("/") 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() app.run(host="0.0.0.0", port=3000, workers=workers, debug=False, access_log=False) Copy code
Simply do nothing but return a response. Although such testing has no practical significance and it is impossible to do nothing in a normal production environment, if all frameworks are tested in this way, they will be on the same starting line to a certain extent.
OK, that's all. At this point, you should know who the asynchronous framework I want to talk about is. Yes, our protagonist today is Sanic * *.
Why use an asynchronous Web framework?
This may be the first question that many little friends think of? I use Django and Flask well and can complete normal tasks. Why use asynchronous Web framework?
At this point, first of all, I want to ask you a question. Who do you think is our biggest enemy in the process of Web development? Think for five seconds and look at my answer:
In the process of Web development, our biggest enemy is not users, but blocking!
Yes, and asynchronous can effectively solve network I/O blocking and file I/O blocking. For specific blocking related articles, it is recommended to view and deeply understand Python asynchronous programming. Because asynchrony can improve efficiency, asynchrony is one of the best ways for Python to improve performance. This is why we chose the asynchronous Web framework.
ecological environment
Some friends may still say, why don't you recommend falcon but Sanic? Obviously, its speed is very fast, which is so much faster than Sanic. 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' '\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...') httpd.serve_forever()
A framework with status codes to be defined and filled in by itself. I think its speed is positive, but how much practical value does it have for developers? Therefore, we choose the framework not to choose the fastest, but to be fast and easy to use.
Most frameworks do not have such an ecological environment, which should be why most Python Web developers are willing to choose Django, Flask and tornado. Because their ecology is too rich compared with other frameworks.
But now it's different. Sanic framework has released the first version of asynchronous Web framework prototype since May 2016. It has gone through five years. In these five years, through continuous technical accumulation, sanic has changed from a faltering small framework to a fast and steady framework.
In the awesome sanic project, a large number of third-party libraries are recorded. You can find any commonly used tools: from API to Authentication, from Development to Frontend, from Monitoring to ORM, from Caching to Queue... There are only third-party extensions you can't think of without it.
production environment
I've seen some small partners in the domestic community asking whether Sanic can be used in the production environment in 2020?
The answer is yes. The author testifies with personal experience that Sanic has been used in the production environment since the end of 19. At that time, Sanic was still 19.9. The author experienced all versions of Sanic from 19.9 to 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 of its creation was to create a Web framework that can be used in production environment. Some frameworks may explicitly state that the built-in Run method in the framework is only used for the test environment, and do not use the built-in Run method for the deployment environment. However, Sanic creates not only an application for the test environment, but also an application that can be directly used in the production environment. Save the trouble of using unicorn and other deployment!
Document perfection
I think the first framework that most Python Web developers learn is Flask or Django, especially Django's documents. I think most of my friends will be satisfied after reading them. Because the old version has Chinese, but the new version, especially the new features, has no Chinese documents at all!!!! It's hard for students who pay attention to the development of Django but English is not their strong point.
However, Sanic has complete Chinese user guides and API documents, which are officially recognized documents initiated by contributors, translated and contributed by translators and published by Sanic's official team. Maybe some friends will say that Flask also has perfect Chinese documents, but it is on different sites. All Sanic documents are officially released and supported by Sanic. At present, Sanic continues to support Korean, Portuguese and other languages.
Community guidance
Different from other frameworks, you may be able to find forums and channels on Baidu, but these are localized and sinicized. The operators are often unofficial and mixed with a lot of advertisements. Obviously, if it is officially operated, it is impossible to allow this to happen.
Sanic is different from other communities. All forums and channels are completely officially operated. Here, you can ask questions to core developers, and sanic's official release manager is also very happy to answer all kinds of questions. You can also share your experience with like-minded users. This is a completely open environment
Sanic currently uses forums, distribute, github issues, twitter and Stackoverflow
You can pay attention to Sanic's development and seek community help in the above ways.
What are you waiting for? Why don't you try it? Finally, it ends with Sanic's vision: Build Faster, Run Faster!
Python advanced notes, latest interview review notes PDF, My GitHub
end of document
Your favorite collection is my greatest encouragement!
Welcome to follow me, share Python dry goods and exchange Python technology.
If you have any opinions on the article or any technical problems, please leave a message in the comment area for discussion!