Table of Contents
1. How WSGI works
2. How ASGI works
3. Using synchronous and asynchronous functions in ASGI
4. Web framework that supports ASGI
Home Backend Development Python Tutorial ASGI explained: The future of Python web development

ASGI explained: The future of Python web development

Apr 12, 2023 pm 10:37 PM
python web asgi

​Translator|Li Rui

Reviewer|Sun Shujuan

Python web applications have long followed the Web Server Gateway Interface (WSGI) standard, which The standard describes how they communicate with web servers. WSGI, originally introduced in 2003 and updated in 2010, relies only on easy-to-implement features that are natively available in Python 2.2. As a result, WSGI was quickly integrated into all major Python web frameworks and became the cornerstone of Python web development.

Fast forward to 2022. Python2 has been deprecated and Python now has native syntax for handling asynchronous operations such as network calls. WSGI and other standards that assume synchronous behavior by default fail to take advantage of the performance and efficiency gains of asynchronous. This in turn means that WSGI cannot handle high-level protocols like WebSocket efficiently.

Enter ASGI, which is the Asynchronous Server Gateway Interface. Similar to WSGI, ASGI describes a common interface between Python web applications and web servers. Unlike WSGI, ASGI allows multiple asynchronous events per application. Additionally, ASGI supports both synchronous and asynchronous applications. Developers can migrate legacy synchronous WSGI web applications to ASGI or build new asynchronous web applications using ASGI.

1. How WSGI works

The working principle of WSGI is to expose Python functions to the web server, usually named as an application or app. This function takes two parameters:

  • #environ: A dictionary containing information about the current request and environment variables provided by the web server.
  • start_response: Will be used to start the function that sends the HTTP response back to the client.

The data returned by the function constitutes the response body.

A simple application function might look like this:​

def application(environ, start_response):

 start_response('200 OK', [('Content-Type', 'text/plain')])

 return [b'Greetings universe']
Copy after login

If you are using a WSGI-compatible web framework (such as Flask ), then the framework itself will provide an application functionality and all its components will be automatically connected.

WSGI has two disadvantages: First, WSGI only handles one request and response at a time and assumes that the response will be returned immediately. There is no way to handle long-held connections, such as WebSocket or long-polling HTTP connections.

Secondly, WSGI is only synchronous. Even with multi-threaded connection pooling, each connection blocks until it returns a response. Many WSGI setups are able to handle thread pools and process pools, but these are limited by the synchronization of the WSGI interface itself.

2. How ASGI works

ASGI is similar in appearance to WSGI. Like WSGI, developers can define an application function object, but it is an asynchronous function with three parameters instead of two:

scope: Contains information about the current request A dictionary of information, similar to environ in WSGI, but the details of the naming convention are slightly different.

send: An asynchronous callable function that allows the application to send messages back to the client.

receive: Asynchronous callable function that allows the application to receive messages from the client.

A simple ASGI application function looks like this:

async def application(scope, receive, send):
 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 after login

Like the WSGI Web framework, the ASGI Web framework will generate its own application () function and connect them as needed.

The most obvious difference from ASGI is the use of asynchronous metaphors throughout the function. The function itself is asynchronous, where the HTTP headers and response body are sent via two separate await send() commands. This way, the functions themselves and their send commands don't block anything; they can be intertwined with the application's calls and sent from many other connections simultaneously.

receive is not used in this example, but it is also an asynchronous function. It allows receiving the request body without blocking other operations. Requests and responses can be passed incrementally to or from the server in this manner - something that cannot be done well, or perhaps at all, with WSGI.

3. Using synchronous and asynchronous functions in ASGI

When using ASGI, you need to use as many asynchronous functions and async-friendly libraries as possible. It pays to get into the habit of using async, as the problems with using synchronous-only code can be serious. Any long call to a synchronous function will block the entire call chain, making the benefits of using async almost gone.

If you encounter problems when using long-running synchronous calls, you need to use asyncio.run_in_executor to outsource the call to a thread pool or process pool. Thread pools should be used whenever waiting for external events or non-CPU-intensive tasks. The process pool should be used for CPU-intensive local tasks.

For example, if there is a route in a web application that can call a remote website, then threads should be used. Or better yet, use the aiohttp library that makes asynchronous HTTP requests. If you want to call the Pillow image library to resize the image, you should probably use run_in_executor with a process pool. Although there is some slight overhead in transferring data back and forth between processes, using run_in_executor does not block other events.

4. Web framework that supports ASGI

By implementing the application() object, ASGI Web applications can be written manually. But in most cases, it's simpler to use an asynchronous native, ASGI-centric Python web framework. Here are some common ASGI-compatible web frameworks:

Starlette and FastAPI: These emerging frameworks (FastAPI is built on top of Starlette) are async-first, so they all support ASGI No wonder. If you are developing web applications from scratch, then they are the most modern and cutting-edge web frameworks for Python.

Quart: While the major Python web framework Flask does support ASGI, Flask is not designed to leverage async metaphors from the inside out. Quart from GitLab uses Flask's syntax and metaphors but allows for asynchronous route handlers.

Django 3.0 and above: Starting from Django 3.0, the prestigious Django web framework supports ASGI. Support for asynchronous code in Django applications was added in Django 3.1, rather than just being able to mount Django on ASGI handlers. For a framework not known for execution speed, the presence of async brings better performance to those who choose to take advantage of it.

Original link: https://www.infoworld.com/article/3658336/asgi-explained-the-future-of-python-Web-development.html​

The above is the detailed content of ASGI explained: The future of Python web development. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1270
29
C# Tutorial
1249
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles