Table of Contents
Analysis of the execution order of await keyword in Python asynchronous programming
in conclusion
Home Backend Development Python Tutorial In Python, why does ws.send_text("1") have to wait for load_dataset("beans") to be executed before it is completed?

In Python, why does ws.send_text("1") have to wait for load_dataset("beans") to be executed before it is completed?

Apr 01, 2025 pm 04:00 PM
python Browser ai Why

Why ws.send_text(

Analysis of the execution order of await keyword in Python asynchronous programming

This article discusses the execution order of await keyword in Python asynchronous programming, especially the scenario of combining FastAPI and WebSocket. A common misconception is that the code after await is executed immediately, and this is not always the case.

The following code example demonstrates this problem:

 from fastapi import FastAPI, WebSocket
from datasets import load_dataset

app = FastAPI()

@app.websocket("/")
async def h(ws: WebSocket):
    await ws.accept()
    await ws.send_text("1")
    dataset = load_dataset("beans") # blocking operation await ws.send_text("2")
Copy after login

Intuitively, we expect "1" to be sent first, then load the dataset, and finally "2". But in reality, the sending of "1" will block until load_dataset("beans") completes. This is because load_dataset("beans") is a synchronous (blocking) function that prevents subsequent execution of the asynchronous function.

In order to observe the execution order more clearly, we modify the code and add the timestamp:

 from datetime import datetime
from datasets import load_dataset
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse

app = FastAPI()

# ... (HTML code remains the same) ...

@app.websocket("/ws")
async def h(ws: WebSocket):
    await ws.accept()
    await ws.send_text(f"1: {datetime.now()}")
    dataset = load_dataset("beans")
    print(f"time: {datetime.now()} => dataset: {dataset}")
    await ws.send_text(f"2: {datetime.now()}")
    While True:
        data = await ws.receive_text()
        await ws.send_text(f"Message text was: {data}, datetime: {datetime.now()}")
Copy after login

Run the modified code and you will find that "1" is indeed sent to the client first, and the browser receives the websocket information. This proves that ws.send_text("1") is executed first. However, the blocking feature of load_dataset("beans") results in a sending delay of "2".

in conclusion

await keyword only waits for the asynchronous operation to complete. If await is followed by a synchronous function, the execution of this synchronous function will block the entire asynchronous function until the synchronous function is executed. Therefore, in asynchronous functions, blocking operations should be avoided as much as possible, or asynchronous alternatives should be used to improve efficiency and response speed. In the above example, if load_dataset has an asynchronous version, it should be used first.

The above is the detailed content of In Python, why does ws.send_text("1") have to wait for load_dataset("beans") to be executed before it is completed?. 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 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
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
How reliable is Binance Plaza? How reliable is Binance Plaza? May 07, 2025 pm 07:18 PM

Binance Square is a social media platform provided by Binance Exchange, aiming to provide users with a space to communicate and share information related to cryptocurrencies. This article will explore the functions, reliability and user experience of Binance Plaza in detail to help you better understand this platform.

The latest download tutorial for Ouyi OKX6.118.0 version The latest download tutorial for Ouyi OKX6.118.0 version May 07, 2025 pm 06:51 PM

The latest download tutorial for Ouyi OKX6.118.0 version: 1. Click on the quick link in the article; 2. Click on the download (if you are a web user, please register the information first). The latest Android version v6.118.0 optimizes some functions and experiences to make trading easier. Update the app now to experience a more extreme trading experience.

2025 Binance Online Web Address 2025 Binance Online Web Address May 07, 2025 pm 06:54 PM

As the world's leading cryptocurrency exchange, Binance is always committed to providing users with a safe and convenient trading experience. Over time, Binance has continuously optimized its platform features and user interface to meet the changing needs of users. In 2025, Binance launched a new login portal aimed at further improving the user experience.

2025 Binance Binance Exchange Latest Login Portal 2025 Binance Binance Exchange Latest Login Portal May 07, 2025 pm 07:03 PM

As the world's leading cryptocurrency exchange, Binance is always committed to providing users with a safe and convenient trading experience. Over time, Binance has continuously optimized its platform features and user interface to meet the changing needs of users. In 2025, Binance launched a new login portal aimed at further improving the user experience.

Eagle's own crawler function image database Eagle's own crawler function image database May 07, 2025 pm 04:36 PM

Eagle is a powerful image database software with built-in crawler function that can batch capture pictures on Huabaiwang to meet your needs for image management. Eagle not only automatically recognizes the tone of the picture, but also supports finding the picture through color. In addition, it also provides various functions such as shape search, source search and size search to help you easily manage and find pictures. Whether you are using Windows, Mac or ChromeOS, Eagle can run smoothly in various environments to meet your multi-platform needs. Eagle also provides convenient browser plug-ins that support batch saving of pictures on the current web page. You can quickly save screenshots, original web page images or local files, and use simple drag and drop operations to transfer your favorite pictures

Python development_python installation Python development_python installation May 07, 2025 pm 04:33 PM

Python can run on a variety of platforms, including our common ones: Windows, Unix, Linux, and Macintosh. This article will introduce in detail the process of installing Python in Windows operating system. My operating system is Windows 7, 32-bit version. When installing Python, we can choose to install it from the source code or select the already compiled binary version for installation. I chose the latter here. Step 1 Download the installation package. We download the installation package of Python from the official Python website: http://www.python.org. The version I selected is: python-3.3.2.msi click to download, I

.NET Core Quick Start Tutorial 1. The beginning: Talking about .NET Core .NET Core Quick Start Tutorial 1. The beginning: Talking about .NET Core May 07, 2025 pm 04:54 PM

1. The Origin of .NETCore When talking about .NETCore, we must not mention its predecessor .NET. Java was in the limelight at that time, and Microsoft also favored Java. The Java virtual machine on the Windows platform was developed by Microsoft based on JVM standards. It is said to be the best performance Java virtual machine at that time. However, Microsoft has its own little abacus, trying to bundle Java with the Windows platform and add some Windows-specific features. Sun's dissatisfaction with this led to a breakdown of the relationship between the two parties, and Microsoft then launched .NET. .NET has borrowed many features of Java since its inception and gradually surpassed Java in language features and form development. Java in version 1.6

usdt trc20 transfer fee usdt trc20 transfer fee May 07, 2025 pm 02:42 PM

The USDT TRC20 transfer fee is affected by network congestion, transaction size and user-selected rates. Optimization fees can be achieved by selecting transaction time, adjusting rates and using batch transactions.

See all articles