


Why does ws.send_text("1") execute before load_dataset("beans") in FastAPI?
FastAPI asynchronous programming with await
keywords: ws.send_text()
and load_dataset()
execution order
This article discusses the execution order of ws.send_text()
and load_dataset()
functions when using async
/ await
for asynchronous programming in the FastAPI framework. In the previous code example, there was a misunderstanding: ws.send_text("1")
seems to have to wait for load_dataset("beans")
to complete before execution. In fact, this is not the case.
The key is to understand the role of the await
keyword and the characteristics of load_dataset()
function. await
is only used to wait for the asynchronous operation to complete. ws.send_text()
is an asynchronous operation, so await ws.send_text("1")
will wait for the message to be sent to complete. However, load_dataset("beans")
is a synchronous blocking operation that blocks the current coroutine until the dataset loads.
Code execution process analysis:
-
await ws.accept()
: Wait for the WebSocket connection to be established. -
await ws.send_text("1")
: Send the message "1" asynchronously, and continue to execute after this operation is completed. -
dataset = load_dataset("beans")
: The synchronous blocking operation begins, the program pauses here untilload_dataset("beans")
downloads and loads the dataset from remotely and completes. -
await ws.send_text("2")
: Send the message "2" asynchronously, and you also need to wait for the sending to complete.
Experimental verification and interpretation of results:
The experimental results clearly show that the browser side receives "1" first, and then "2", which is consistent with the blocking characteristic of load_dataset("beans")
. Although ws.send_text("1")
is executed first, the blocking of load_dataset("beans")
causes the sending of "2" to be delayed until the dataset is loaded.
Improved code to implement concurrency:
If load_dataset("beans")
and ws.send_text("1")
are required to execute concurrently, load_dataset("beans")
needs to be transformed into asynchronous operations. This usually requires the use of asynchronous IO libraries, such as aiohttp
, to download data. Here is an improved example (assuming that aiohttp
is used and an asynchronous load_dataset_async
function is implemented):
import asyncio 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() task = asyncio.create_task(load_dataset_async("beans")) # Asynchronously load dataset await ws.send_text(f"1: {datetime.now()}") dataset = await task # Await the dataset loading task print(f"time: {datetime.now()} => dataset: {dataset}") await ws.send_text(f"2: {datetime.now()}") # ... (rest of the code remains the same) ...
Create asynchronous tasks through asyncio.create_task()
, load_dataset_async("beans")
can be executed concurrently in the background without blocking the main coroutine.
Summary: ws.send_text("1")
was executed first in the original code, but the synchronous blocking feature of load_dataset("beans")
determines the execution order of subsequent operations. To achieve concurrency, the data loading operation must be asynchronous.
The above is the detailed content of Why does ws.send_text("1") execute before load_dataset("beans") in FastAPI?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The main reasons why you cannot log in to MySQL as root are permission problems, configuration file errors, password inconsistent, socket file problems, or firewall interception. The solution includes: check whether the bind-address parameter in the configuration file is configured correctly. Check whether the root user permissions have been modified or deleted and reset. Verify that the password is accurate, including case and special characters. Check socket file permission settings and paths. Check that the firewall blocks connections to the MySQL server.

Remote Senior Backend Engineer Job Vacant Company: Circle Location: Remote Office Job Type: Full-time Salary: $130,000-$140,000 Job Description Participate in the research and development of Circle mobile applications and public API-related features covering the entire software development lifecycle. Main responsibilities independently complete development work based on RubyonRails and collaborate with the React/Redux/Relay front-end team. Build core functionality and improvements for web applications and work closely with designers and leadership throughout the functional design process. Promote positive development processes and prioritize iteration speed. Requires more than 6 years of complex web application backend

MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

There are many reasons why MySQL startup fails, and it can be diagnosed by checking the error log. Common causes include port conflicts (check port occupancy and modify configuration), permission issues (check service running user permissions), configuration file errors (check parameter settings), data directory corruption (restore data or rebuild table space), InnoDB table space issues (check ibdata1 files), plug-in loading failure (check error log). When solving problems, you should analyze them based on the error log, find the root cause of the problem, and develop the habit of backing up data regularly to prevent and solve problems.

The MySQL primary key cannot be empty because the primary key is a key attribute that uniquely identifies each row in the database. If the primary key can be empty, the record cannot be uniquely identifies, which will lead to data confusion. When using self-incremental integer columns or UUIDs as primary keys, you should consider factors such as efficiency and space occupancy and choose an appropriate solution.

MySQL refused to start? Don’t panic, let’s check it out! Many friends found that the service could not be started after installing MySQL, and they were so anxious! Don’t worry, this article will take you to deal with it calmly and find out the mastermind behind it! After reading it, you can not only solve this problem, but also improve your understanding of MySQL services and your ideas for troubleshooting problems, and become a more powerful database administrator! The MySQL service failed to start, and there are many reasons, ranging from simple configuration errors to complex system problems. Let’s start with the most common aspects. Basic knowledge: A brief description of the service startup process MySQL service startup. Simply put, the operating system loads MySQL-related files and then starts the MySQL daemon. This involves configuration
