Protocol in Python's asyncio

In the context of Python's asyncio library, a protocol is a set of APIs that directly wrap sockets, providing a clean interface for reading and writing data. Protocols are part of the lower-level transport and protocol APIs, which utilize a callback style design. They are essential for managing the lifecycle of a connection, including establishing a connection, writing data, and processing responses. Protocols work in conjunction with transports, which handle data transmission and invoke protocol methods when specific events occur.

Understanding Protocols and Transports

A protocol in asyncio is essentially a Python class that defines operations for managing a connection's lifecycle. It is not to be confused with network protocols like HTTP or FTP. Instead, it refers to the class that handles the connection's lifecycle events. The transport is responsible for the actual data transmission and calls the protocol's methods when events such as connection establishment or data reception occur.

Figure 8.2 A transport calls methods on a protocol when events happen. A protocol can write data to a transport. Figure 8.2 A transport calls methods on a protocol when events happen. A protocol can write data to a transport.

Implementing a Protocol

To illustrate how protocols and transports work together, let's implement a simple application that performs an HTTP GET request. We will define a class that extends asyncio.Protocol and implement methods to handle the request, receive data, and manage connection errors.

Example: HTTPGetClientProtocol

Below is an implementation of a protocol class named HTTPGetClientProtocol:

import asyncio
from asyncio import Transport, Future, AbstractEventLoop
from typing import Optional
 
 
class HTTPGetClientProtocol(asyncio.Protocol):
 
    def __init__(self, host: str, loop: AbstractEventLoop):
        self._host: str = host
        self._future: Future = loop.create_future()
        self._transport: Optional[Transport] = None
        self._response_buffer: bytes = b''
 
    async def get_response(self):                                  #1
        return await self._future
 
    def _get_request_bytes(self) -> bytes:                         #2
        request = f"GET / HTTP/1.1\r\n" \
                  f"Connection: close\r\n" \
                  f"Host: {self._host}\r\n\r\n"
        return request.encode()
 
    def connection_made(self, transport: Transport):
        print(f'Connection made to {self._host}')
        self._transport = transport
        self._transport.write(self._get_request_bytes())           #3
 
    def data_received(self, data):
        print(f'Data received!')
        self._response_buffer = self._response_buffer + data       #4
 
    def eof_received(self) -> Optional[bool]:
        self._future.set_result(self._response_buffer.decode())    #5
        return False
 
    def connection_lost(self, exc: Optional[Exception]) -> None:   #6
        if exc is None:
            print('Connection closed without error.')
        else:
            self._future.set_exception(exc)
#1 Await the internal future until we get a response from the server.
#2 Create the HTTP request.
#3 Once we’ve established a connection, use the transport to send the request.
#4 Once we have data, save it to our internal buffer.
#5 Once the connection closes, complete the future with the buffer.
#6 If the connection closes without error, do nothing; otherwise, complete the future with an exception.

Using the Protocol

To make a real HTTP request using the protocol, we utilize the create_connection coroutine method from the asyncio event loop. This method creates a socket connection to a specified host and wraps it in a transport. It also requires a protocol factory, which is a function that creates instances of the protocol class.

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())

In this example, the make_request function creates a new HTTPGetClientProtocol instance using a protocol factory. The create_connection coroutine is called with the host and port, returning both a transport and the protocol instance. The get_response coroutine of the protocol is awaited to receive the server's response. The main coroutine then prints the response.

FAQ (Frequently asked questions)

What happens when events occur in a transport?

Can a protocol write data to a transport?

What design style do transport and protocol APIs use in asyncio?

What happens when data is received in the HTTPGetClientProtocol class?

What does the HTTPGetClientProtocol class do if the connection is lost without error?