This article is participating in “Python Theme Month”, check out: Python Writing season, and show off your Python article – 2000 yuan for a limited prize

Asgi is an asynchronous communication service specification. The client initiates a service call but does not wait for the result. The caller immediately continues its work, not caring about the result. If the caller is interested in the result, there are mechanisms for it to be returned by the callback method at any time. ASGI tries to maintain a simple application interface while providing abstractions that allow data to be sent and received by any application process at any time. It also describes a new sequence format that is compatible with HTTP request responses and WebSocket data frames. Allow these protocols to be transmitted over the network or local sockets, and allow different protocols to be assigned to different processes.

#Asgi example async def application(scope, receive, send): event = await receive() ... await send({"type": "websocket.send", ... })Copy the code

ASGI framework

You can run any ASGI framework using Uvicorn, Daphne or Hypercorn

For small services, you can also write ASGI applications directly. For example, the asynchronous framework I wrote earlier.

There are several asynchronous frameworks in Python that support ASGI

Starlette

Starlette is a lightweight ASGI framework/toolkit. It is ideal for building high-performance asynchronous services and supports HTTP and WebSockets.

The Django Channels ASGI specification was originally designed for Django Channels.

Channels is slightly different from other ASGI frameworks in that it provides an asynchronous front end on top of the thread framework back end.

Django Channels also supports Websockets, background tasks, and long-running connections, while the application code still runs in the context of standard threads

Quart

Quart is an ASGI Web framework similar to Flask. Quart is not only similar to Flask, but also compatible with the Flask API!

The authors of the framework wanted to keep the Flask style, just adding asynchronous, WebSocket, and HTTP 2 support.

Therefore, you can learn how to use Quart from the Flask documentation, just remember that the functions in Quart are asynchronous.

A simple Quart service:

from quart import Quart

app = Quart(name)

@app.route(‘/’) async def hello(): return ‘hello’app.run(

Since Quart evolved from Flask, all of Flask’s functionality is available: routing, middleware, sessions, templates, blueprints, etc

ASGI server

Uvicorn is a fast ASGI server built on UvLoop and HttpTools and is an important part of Python’s asynchronous ecology.

Uvicorn currently supports HTTP / 1.1 and WebSockets, with future support for HTTP / 2 planned.

Python 3.5 or above, Uvicorn installed,

PIP install uvicorn

async def app(scope, receive, send): assert scope['type'] == 'http' await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'text/plain'], ] }) await send({ 'type': 'http.response.body', 'body': b'Hello, world! '})Copy the code

Run the following command,

Uvicorn Demo: After the app service is started, we can access the service through the browser. The default port is 8000

Daphne The Daphne Server was the first ASGI server to support Django Channels

Daphne It runs widely in production and supports HTTP / 1.1, HTTP / 2, and WebSockets.

The installation and running commands are as follows:

PIP install daphne daphne app: app Is similar to the uvicorn command. App is the name of the file and app is the application

Hypercorn

Hypercorn was originally part of the framework Quart and was then separated as a separate ASGI server

Also, Hypercorn supports HTTP/1.1, HTTP/2, and WebSockets.

The installation and running commands are as follows:

pip install hypercorn hypercorn app:App

FastAPI

FastAPI is an API framework based on Starlette and Pydantic, inspired by previous versions of the APISta server

Use Python 3.6+ type declaration to write API function parameters, and get automatic data conversion, data validation.

The main feature of FastApi is fast, very high performance, in line with NodeJS and Go, one of the fastest Python frameworks available

It also automatically generates an interactive API document UI. After writing an API, you can use the API with a standard compliant UI such as SwaggerUI, ReDoc, etc.

Its characteristics are as follows:

Fast: Very high performance thanks to Starlette and Pydantic; Starlette for route matching and Pydantic for data validation

Development efficiency: Improved function development efficiency by 200% to 300%

Bug reduction: 40% reduction in errors caused by developer carelessness

Intelligence: The internal type annotations are perfect, and the editor can be completed automatically everywhere

Simplicity: The framework is easy to use and the documentation is easy to read

Brevity: Minimizes code duplication and achieves rich functionality with different parameter declarations

Robust: Code can be written for use online, and interactive documents are automatically generated

Standardization: compatibility with API related open standards

It uses Python’s type annotations

For example: Install the dependent library PIP install fastAPI PIP install uvicorn

Import uvicorn from fastAPI import FastAPI # Similar to app = Flask(__name__) app = fastAPI () # Bind route and view functions @app.get("/") async Def root(): return {"message": "Hi juejin"} if __name__ == "__main__", otherwise RuntimeError will be raised: This event loop is already running if __name__ == '__main__': The first parameter "main:app" means this, and the first parameter "main:app" means this. Uvicorn. run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)Copy the code

FastAPI features: Type checking, automatic Swagger UI, asyncio support, powerful dependency injection system

conclusion

1. Performance Improvement Note: For large projects in production environments, the FastAPI takes advantage of the asynchronous and lightweight nature of the fastAPI to greatly improve performance. But the application of asynchrony is not easy. Asynchronous fastAPI is not hard to write. If the logic is not complex, it is easy to add await with your eyes closed. But if you’re dealing with complex systems. One place asynchronous, everywhere asynchronous. Whether to use it or not may be a matter of opinion. Lightweight also means that, like Flask, there’s a lot of diy to do. It’s not a one-stop shop like Django. So FastAPI may be taking over flask, but it’s still hard to challenge Django. Most importantly, python was chosen for the back end. Maybe it wasn’t performance sensitive in the first place. It focuses on the efficiency and ecology of Python development. From a development efficiency + performance point of view, the fastapi will face stiff competition from go for the most part. The fastapi has a big advantage only when it is used in conjunction with python’s existing ecosystem. Imagine an existing Python project that runs into a performance bottleneck but doesn’t want to leave The Python environment or incur the cost of switching languages. So FastAPI is a great future.

  1. API documentation, type detection, and dependency injection FastAPI fully embraces the typing type system, is highly integrated with OpenAPI (Swagger UI), and, as its name suggests, fastAPI is “fast” enough for both performance and development efficiency from an API development perspective. Provides a great deal of support for API documentation. Without any configuration, the backend simply writes the endpoint, and a detailed API documentation is automatically generated. It’s a huge advantage for small projects. Type detection and dependency injection are the cornerstones of the API documentation, and they focus on the “feel” around the framework. Inspect captures the endpoint argument and knows exactly what each API needs and returns. This will make you feel like the framework is really spiritual. I am absolutely full of praise for that.

  2. Flask will use the fastapi, and the fastapi learning curve is very smooth. There’s a lot to learn from the bottom up. It is highly recommended that students have time to go over starlette, Uvicorn, fastAPI source code. Not as much as Django combined.

  3. Python’s asynchronous development is a bit slow, and the FastAPI alone isn’t going to hold the day. For example, there is no fully reliable asynchronous ORM. A lot of things have to be built with wheels. On small projects, this may not matter very much. Writing code directly can be faster than configuring plug-ins. But it will greatly affect its adoption into online production environments. In summary, think of the fastapi as a new flask plus. If you have a reason to use flask, you also have a reason to use fastapi in the future.