🔧 AI Nachrichten The Next Terrorist Attack Is Predictable(10.09.2026 um 23:41 Uhr)
🔧 AI Nachrichten Could A.I. Really Kill All Humans?(10.09.2026 um 23:53 Uhr)
🔧 AI Nachrichten Amazon Prime Video Uses A.I. for Lip-Synced Translations(11.09.2026 um 01:56 Uhr)
🔧 AI Nachrichten McClatchy Makes Deep Job Cuts to Newspapers Around the Country(11.09.2026 um 04:25 Uhr)
🔧 AI Nachrichten Law schools tell students to put AI away(07.09.2026 um 16:37 Uhr)
🔧 AI Nachrichten Can Huawei build China’s answer to ASML?(08.09.2026 um 04:57 Uhr)
🔧 AI Nachrichten AI is ushering in an era of mass toe-treading at work(08.09.2026 um 06:00 Uhr)
🔧 AI Nachrichten The Next Terrorist Attack Is Predictable(10.09.2026 um 23:41 Uhr)
🔧 AI Nachrichten Could A.I. Really Kill All Humans?(10.09.2026 um 23:53 Uhr)
🔧 AI Nachrichten Amazon Prime Video Uses A.I. for Lip-Synced Translations(11.09.2026 um 01:56 Uhr)
🔧 AI Nachrichten McClatchy Makes Deep Job Cuts to Newspapers Around the Country(11.09.2026 um 04:25 Uhr)
🔧 AI Nachrichten Law schools tell students to put AI away(07.09.2026 um 16:37 Uhr)
🔧 AI Nachrichten Can Huawei build China’s answer to ASML?(08.09.2026 um 04:57 Uhr)
🔧 AI Nachrichten AI is ushering in an era of mass toe-treading at work(08.09.2026 um 06:00 Uhr)

🔧 Programmierung 🕛 vor 1 Jahr 11 Min Lesezeit
0

Mastering Python Async IO with FastAPI

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht


select, poll, and epoll can all achieve I/O multiplexing. Compared with select and poll, epoll has better performance. Linux generally uses epoll by default, and macOS uses kqueue, which is similar to epoll and has similar performance.






Socket Server Using Event Loops






CODE
import selectors
import socket

# Create a selectors object, equivalent to the implementation of epoll, when running on Linux
sel = selectors.DefaultSelector()

# Request reception event handling function. Accept new connections and register read events
def accept(sock, mask):
conn, addr = sock.accept() # Accept the connection
print('Accepted connection from', addr)
conn.setblocking(False)
sel.register(conn, selectors.EVENT_READ, read) # Register the read event

# Request reading event handling function. Read request data and send an HTTP response, then close the connection.
def read(conn, mask):
data = conn.recv(100) # Read data from the connection
print('response to')
response = "HTTP/1.1 200 OK\r\n" \
"Content-Type: application/json\r\n" \
"Content-Length: 18\r\n" \
"Connection: close\r\n" \
"\r\n" \
"{\"Hello": \"World\"}"
conn.send(response.encode()) # Echo the data
print('Closing connection')
sel.unregister(conn) # Unregister the event
conn.close() # Close the connection

# Create a server socket
sock = socket.socket()
sock.bind(('localhost', 8000))
sock.listen()
sock.setblocking(False)

# Register the accept event
sel.register(sock, selectors.EVENT_READ, accept)

print("Server is running on port 8000...")

# Event loop
while True:
# This will block when there are no requests
events = sel.select() # Select the file descriptors (events) that are ready
print("events length: ", len(events))
for key, mask in events:
callback = key.data # Get the event handling function
print("handler_name:", callback.__name__)
callback(key.fileobj, mask) # Call the event handling function






Start the server socket to monitor the specified port. If running on a Linux system, selectors uses epoll as its implementation by default. The code uses epoll to register a request reception event (accept event). When a new request arrives, epoll will trigger and execute the event handling function, and at the same time, register a read event (read event) to process and respond to the request data. When accessed from the web side with http://127.0.0.1:8000/, the return result is the same as that of Example 1. Server running log:




CODE
Server is running on port 8000...
events length: 1
handler_name: accept
Accepted connection from ('127.0.0.1', 60941)
events length: 1
handler_name: read
response to
Closing connection









Socket Server



Directly use Socket to start a server. When accessed with a browser at http://127.0.0.1:8080/ or using curl http://127.0.0.1:8080/, it will return {"Hello": "World"}




CODE
import socket
from datetime import datetime

# Create a TCP socket
server_socket = socket.socket()

# Bind the socket to the specified IP address and port number
server_socket.bind(('127.0.0.1', 8001))

# Start listening for incoming connections
server_socket.listen(5)

# Loop to accept client connections
while True:
print("%s Waiting for a connection..." % datetime.now())
client_socket, addr = server_socket.accept() # This will block, waiting for client connections
print(f"{datetime.now()} Got connection from {addr}")

# Receive client data
data = client_socket.recv(1024)
print(f"Received: {data.decode()}")

# Send response data
response = "HTTP/1.1 200 OK\r\n" \
"Content-Type: application/json\r\n" \
"Content-Length: 18\r\n" \
"Connection: close\r\n" \
"\r\n" \
"{\"Hello": \"World\"}"

client_socket.sendall(response.encode())

# Close the client socket
client_socket.close()






When accessed with curl http://127.0.0.1:8001/, Server running log:




CODE
2024-12-27 12:53:36.711732 Waiting for a connection...
2024-12-27 12:54:30.715928 Got connection from ('127.0.0.1', 64361)
Received: GET / HTTP/1.1
Host: 127.0.0.1:8001
User-Agent: curl/8.4.0
Accept: */*









Summary



Asynchronous I/O is implemented at the bottom layer using "coroutines" and "event loops". "Coroutines" ensure that when the thread encounters marked I/O operations during execution, it doesn't have to wait for the I/O to complete but can pause and let the thread execute other tasks without blocking. "Event loops" use the I/O multiplexing technology, constantly cycling to monitor I/O events. When a certain I/O event is completed, the corresponding callback is triggered, allowing the coroutine to continue execution.









.





The unique advantages of



Leapcell Twitter: https://x.com/LeapcellHQ

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen

Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
2 Quellen
Could A.I. Really Kill All Humans?
1 Quelle
The Next Terrorist Attack Is Predictable
1 Quelle
Anthropic Says It Blocked Possible Efforts to Build Biological Weapons
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Mastering Python Async IO with FastAPI

Thematisch verwandte Begriffe: Mastering, Python, Async, with · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...