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
