liveBook · Manning

Create_connection

As explained in Python Concurrency with asyncio

create_connection is an asyncio event-loop coroutine that establishes a socket connection and returns its transport and protocol.

create_connection is an asyncio event-loop coroutine for opening a socket connection to a host and port. It accepts a protocol factory, creates the protocol, wraps the socket in a transport, and returns both objects. section 8.2

Use the protocol to manage application behavior and await its result; retain the transport only when direct transport operations are needed. This lower-level API is not the recommended way to work with streams. section 8.2

HTTP request with a protocol factory

Define a factory that creates HTTPGetClientProtocol, then await loop.create_connection(factory, host=host, port=port). Ignore the returned transport, keep the protocol, and await protocol.get_response() for the HTTP response. section 8.2

Listing 8.2 Using the protocol
import asyncio
from asyncio import AbstractEventLoop
from chapter_08.listing_8_1 import HTTPGetClientProtocol
 
 
async def make_request(host: str, port: int, loop: AbstractEventLoop) -> str:
    def protocol_factory():
        return HTTPGetClientProtocol(host, loop)
 
    _, protocol = await loop.create_connection(protocol_factory, host=host, port=port)
 
    return await protocol.get_response()
 
 
async def main():
    loop = asyncio.get_running_loop()
    result = await make_request('www .example .com', 80, loop)
    print(result)
 
 
asyncio.run(main())

Shows the complete pattern for creating a connection, retaining the protocol, awaiting its response, and running the request. section 8.2

How Python Concurrency with asyncio covers it

How deep it goes
Explains arguments, returned objects, protocol factories, and response awaiting, while stopping short of recommending lower-level stream usage.
Examples
Demonstrates an HTTP GET client that connects to a host, receives an HTTP response, and prints it.
What it assumes
Assumes asyncio coroutines and event loops, while teaching how transports, protocols, and protocol factories cooperate.
What you can do after
Apply it via asyncio to create a custom protocol connection and await the protocol's completed response.
How it connects
Connects the event loop, socket connections, transports, protocols, protocol factories, coroutines, and Futures.

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.