Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize ASGI and Fast Api of python Asynchronous

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to achieve python asynchronous ASGI and Fast Api". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to achieve python asynchronous ASGI and Fast Api".

Asgi is an asynchronous communication service specification. The client initiates a service call but does not wait for the result. The caller immediately continues his work and does not care about the result. If the caller is interested in the result, there are mechanisms that allow it to be returned by the callback method at any time.

ASGI attempts to maintain a simple application interface, providing abstractions that allow data to be sent and accepted by any application process at any time. And also describes a new, compatible HTTP request response and WebSocket data frame sequence format. Allow these protocols to be transmitted over the network or local socket, and to 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 in that it provides an asynchronous front end on the back end of the threading framework.

At the same time, Django Channels supports WebSocket, background tasks and long-running connections, while application code is still running 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 Flask API!

The authors of the framework want to retain the style of Flask, but add asynchronous, WebSocket, and HTTP 2 support to it.

Therefore, you can learn the use of Quart from Flask documents, just remember that the functions in Quart are asynchronous.

A simple Quart service:

From quart import Quartapp = Quart (name) @ app.route ("/") async def hello () return "hello" app.run ()

Is it very similar to Flask, only with an asynchronous async?

Because Quart is derived from Flask, all the functions of Flask are available: routing, middleware, session, template, blueprint, etc.

ASGI server

Uvicorn is a fast ASGI server. Uvicorn is built on uvloop and httptools and is an important member of the Python asynchronous ecology.

Uvicorn currently supports HTTP / 1.1and WebSockets, and plans to support HTTP / 2 in the future.

Version requires Python 3.5 or above, Uvicorn installation

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

Run the command as follows

Uvicorn demo:app

After the service starts, we can locate the service through the browser. The default port is 8000.

Daphne

Daphne server is the earliest ASGI server to support Django Channels

Daphne is widely used in production and supports HTTP / 1.1 HTTP / 2 and WebSockets.

The commands to install and run are as follows:

The pip install daphne daphne app:App command is similar to the uvicorn command, where app is the file name and APP is the application

Hypercorn

Hypercorn was originally part of the framework Quart and then split into a separate ASGI server

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, inspired by previous APISta server versions

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

The main feature of FastApi is fast, very high performance, on a par with NodeJS and Go, 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,ReDoc to use API.

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: function development efficiency increases by 200% to 300%

Reduce bug: reduce errors caused by developers' carelessness by 40%

Intelligence: the internal type annotation is very perfect, and the editor can complete it automatically everywhere.

Simplicity: the framework is easy to use and the document is easy to read

Brevity: minimize code repetition and achieve rich functionality through different parameter declarations

Robust: you can write code for online use, and interactive documents are automatically generated

Standardization: compatible with API-related open standards

It uses Python's type annotations

Examples are as follows:

Install dependent libraries first

Pip install fastapipip install uvicornimport uvicornfrom fastapi import FastAPI# is similar to app = Flask (_ name__) app = FastAPI () # bind routing and view function @ app.get ("/") async def root (): return {"message": "Hi juejin"} # must add if _ name__ = = "_ main__" in Windows, otherwise RuntimeError: This event loop is already runningif _ name__ = = "_ main__": # start the service Because our file is called main.py, we need to start app # in main.py. The first parameter "main:app" indicates this meaning, followed by host and port for listening ip and port uvicorn.run (app= "main:app", host= "127.0.0.1", port=8000, reload=True, debug=True).

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

Thank you for your reading, the above is the content of "how to achieve python asynchronous ASGI and Fast Api". After the study of this article, I believe you have a deeper understanding of how to achieve python asynchronous ASGI and Fast Api, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report