liveBook · Manning

Stream API

As explained in Python Concurrency with asyncio

An asyncio stream is a high-level abstraction for creating and managing network connections and reading or writing sequential data.

An asyncio stream is a high-level abstraction for creating and managing network connections and reading or writing sequential data. It hides socket details such as SSL handling and lost connections, making client-server applications easier to build and more robust. section 8.0 section 8.1

Stream APIs provide StreamReader for asynchronous reads and StreamWriter for writes. The open_connection coroutine creates both for a host and port. Reads can wait for a line or a specified number of bytes; writes require drain when buffered output must be flushed. section 8.3

Use streams to:

  • Create HTTP clients that send requests and consume responses without blocking the event loop. section 8.3
  • Process command-line input asynchronously while background tasks, such as multiple queries, continue running. section 8.0
  • Create responsive servers and clients, including chat applications, with asyncio's start_server coroutine. section 8.7

Transports and protocols remain the lower-level foundation. They expose direct socket control through callbacks such as connection_made and data_received, whereas streams package common networking work into easier reader and writer interfaces. section 8.1 section 8.2

Asynchronous HTTP request

Call asyncio.open_connection, write an encoded HTTP request through StreamWriter, await drain, and repeatedly await StreamReader.readline until the response ends.

How Python Concurrency with asyncio covers it

How deep it goes
Explains reader-writer operations, buffering, and lower-level transport foundations, while deferring socket-level implementation details.
Examples
Uses HTTP clients, a non-blocking SQL command-line client, and chat servers and clients as practical applications.
What it assumes
Assumes basic socket-based networking for comparison, then establishes stream usage through progressively simpler reader-writer APIs.
What you can do after
Build it from scratch: create asynchronous network clients and servers using open_connection, StreamReader, StreamWriter, and start_server.
How it connects
Connects streams with sockets, transports and protocols, StreamReader, StreamWriter, asynchronous servers, and client-server applications.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.