Implementation of Python asynchronous asgi and fast API

Time:2021-11-23
catalogue
  • Asgi framework
  • Asgi server
  • FastAPI
  • summary

Asgi is the asynchronous communication service specification. The client initiates a service call but does not wait for the result. The caller immediately continues its work, regardless of the result. If the caller is interested in the result, there are some mechanisms for it to be returned by the callback method at any time.

Asgi attempts to maintain a simple application interface and provide an abstraction that allows data to be sent and accepted by any application process at any time. It also describes a new sequence format compatible with HTTP request response and websocket data frame. Allow these protocols to be transmitted through the network or local socket, 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", ...})

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 written 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.

Django Channels
The asgi specification was originally designed for Django channels.
Channels is slightly different from other asgi frameworks. It provides an asynchronous front end on the back end of the threading framework.
At the same time, Django channels 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 flash, but also compatible with the flash API!
The authors of the framework want to retain the flask style and just add asynchronous, websocket and HTTP 2 support to it.
Therefore, you can learn the usage of Quart from the flash document. 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()

Is it very similar to flask, except for an asynchronous async
Since Quart evolved from flask, all functions of flask are available: routing, middleware, session, template, blueprint, etc

Asgi server

Uvicorn is a fast asgi server. Uvicorn is built based on uvloop and httptools. It is an important member of Python asynchronous ecology.
Uvicorn currently supports HTTP / 1.1 and WebSockets, and plans to support HTTP / 2 in the future.
The version requires Python 3.5 or above, installation of uvicorn,


pip install uvicorn

Examples are as follows:


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!',
    })

The operation command is as follows:,

uvicorn demo:app
After the service is started, we can locate the service through the browser. The default port is 8000

Daphne
Daphne server was the first asgi server to support Django channels
Daphne runs widely in production and supports HTTP / 1.1, http / 2 and WebSockets.

The commands to install and run are as follows:

pip install daphne    Daphne app: app is similar to the uvicon command. App is the file name and app is the application

Hypercorn
Hypercorn was originally part of the quart framework and was then separated into separate asgi servers
Similarly, hypercorn supports HTTP / 1.1, http / 2, and WebSockets
The commands to install and run are as follows:
pip install hypercorn hypercorn app:App

FastAPI

Fastapi is an API framework based on starlette and pydantic, which is inspired by the previous version of apista server
Use Python 3.6 + type declaration to write API function parameters, and obtain automatic data conversion and data verification.
The main feature of fastapi is fast and very high performance. It is in line with nodejs and go. It is one of the fastest Python frameworks available
At the same time, it can automatically generate interactive API document UI. After writing the API interface, you can use standard UI such as swaggerui and redoc to use the API.

Its features are as follows:

  • Fast: it has very high performance, thanks to starlette and pydantic; Starlette is used for route matching and pydantic is used for data verification
  • Development efficiency: function development efficiency increased by 200% to 300%
  • Reduce bugs: reduce errors caused by careless developers by 40%
  • Intelligence: the internal type annotation is very perfect, and the editor can automatically complete everywhere
  • Simple: the framework is easy to use and the document is easy to read
  • Short: minimize code duplication and realize rich functions through different parameter declarations
  • Robust: you can write the code used on the line and automatically generate interactive documents
  • Standardization: compatible with API related open standards
  • It uses Python’s type annotations

Examples are as follows:

Install dependent libraries first


pip install fastapi
pip install uvicorn
import uvicorn
from fastapi import FastAPI

#Similar to app = flask (_ name_)
app = FastAPI()

#Binding routing and view functions
@app.get("/")
async def root():
    return {"message": "Hi juejin"}

#If must be added in windows__ name__ ==  "_main_", otherwise runtimeerror will be thrown: this event loop is already running
if __name__ == '__main__':
    #Start the service. Because our file is called main.py, we need to start the app in main.py
    #The first parameter "main: app" indicates this meaning, and then host and port indicate the listening IP and port
    uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)

Several functions of fastapi: type checking, automatic swagger UI, support for asyncio, and powerful dependency injection system

summary

Performance improvement note: for large projects in the production environment, fastapi uses asynchronous and lightweight features to greatly improve the performance. However, it is not easy to apply asynchrony to practice. The asynchrony of fastapi is not difficult to write. If the logic is not complex, it is very simple to add a few awaits with your eyes closed. But if complex systems are involved. One asynchronous, everywhere asynchronous. There may be different opinions on whether to use it or not. Lightweight also means that like flash, many things need to be DIY. Instead of a one-stop solution like Django. Therefore, fastapi may gradually take over the position of flash, but it is still difficult to challenge Django. The most important point is that Python is selected as the back end. It may not be very sensitive to performance at the beginning. Instead, they focus on the development efficiency and ecology of Python. From the perspective of both development efficiency and performance, fastapi will encounter strong competition from go to a great extent. Only by taking into account the existing ecology of python, fastapi will have great advantages. We can imagine that an existing Python project has encountered a performance bottleneck, but we don’t want to leave the python environment or bear the cost of changing languages. So fastapi is a good future.

API documentation, type detection and dependency injection fastapi fully embrace the typing type system and highly integrate the open API (swagger UI). Just like its name, fastapi is “fast” in terms of API development performance and development efficiency. There is a lot of support for API documentation. No configuration is required. As long as the backend writes the endpoint, a detailed API document will be generated automatically. It is a huge advantage for small projects. Type detection and dependency injection are the cornerstones of API documents. They focus on the “perception” around the framework. Inspect grabs the parameters of the endpoint and clearly knows what each API interface needs and returns. This will make you feel that this framework is really spiritual. I am absolutely full of praise in this regard.

Simplicity and conciseness. If you can use flash, you will get fastapi. The learning curve of fastapi is very smooth. There are many things worth learning from bottom to top. It is highly recommended that students have time to go through the source code of starlet, uvicon and fastapi. It doesn’t add up to Django much.

The related ecology and community are still immature, and the asynchronous development of Python is slightly slow, and fastapi alone can’t hold up a day. For example, there is no fully reliable asynchronous ORM yet. Many things need to make their own wheels. On small projects, this may not have a great impact. Writing code directly may be faster than configuring plug-ins. But it will largely affect its adoption into the online production environment. To sum up, you can think of fastapi as a new flash plus. If you have a reason to adopt flash, you also have a reason to adopt fastapi in the future.

This is the end of this article about the implementation of Python asynchronous asgi and fast API. For more information about Python asynchronous asgi and fast API, please search the previous articles of developpaer or continue to browse the relevant articles below. I hope you will support developpaer in the future!

Recommended Today

Apache sqoop

Source: dark horse big data 1.png From the standpoint of Apache, data flow can be divided into data import and export: Import: data import. RDBMS—–>Hadoop Export: data export. Hadoop—->RDBMS 1.2 sqoop installation The prerequisite for installing sqoop is that you already have a Java and Hadoop environment. Latest stable version: 1.4.6 Download the sqoop installation […]