Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Rewrite examples using streams
  • Loading branch information
tirkarthi committed Jun 18, 2019
commit fee4b7809103007656e35727390c54e1b409e6d5
3 changes: 1 addition & 2 deletions Doc/library/asyncio-eventloop.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1625,8 +1625,7 @@ Wait until a file descriptor received some data using the
:meth:`loop.create_connection` method.

* Another similar :ref:`example <asyncio_example_create_connection-streams>`
using the high-level :func:`asyncio.open_connection` function
and streams.
using the high-level :func:`asyncio.connect` function and streams.


.. _asyncio_example_unix_signals:
Expand Down
4 changes: 2 additions & 2 deletions Doc/library/asyncio-protocol.rst
Original file line number Diff line number Diff line change
Expand Up @@ -810,7 +810,7 @@ data, and waits until the connection is closed::
.. seealso::

The :ref:`TCP echo client using streams <asyncio-tcp-echo-client-streams>`
example uses the high-level :func:`asyncio.open_connection` function.
example uses the high-level :func:`asyncio.connect` function.


.. _asyncio-udp-echo-server-protocol:
Expand Down Expand Up @@ -977,7 +977,7 @@ Wait until a socket receives data using the

The :ref:`register an open socket to wait for data using streams
<asyncio_example_create_connection-streams>` example uses high-level streams
created by the :func:`open_connection` function in a coroutine.
created by the :func:`asyncio.connect` function in a coroutine.

.. _asyncio_example_subprocess_proto:

Expand Down
58 changes: 27 additions & 31 deletions Doc/library/asyncio-stream.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,16 @@ streams::
import asyncio

async def tcp_echo_client(message):
reader, writer = await asyncio.open_connection(
'127.0.0.1', 8888)
stream = await asyncio.connect('127.0.0.1', 8888)
Comment thread
tirkarthi marked this conversation as resolved.
Outdated

print(f'Send: {message!r}')
await writer.write(message.encode())
stream.write(message.encode())
Comment thread
tirkarthi marked this conversation as resolved.
Outdated

data = await reader.read(100)
data = await stream.read(100)
print(f'Received: {data.decode()!r}')

print('Close the connection')
await writer.close()
await stream.close()

asyncio.run(tcp_echo_client('Hello World!'))

Expand Down Expand Up @@ -366,22 +365,21 @@ Examples
TCP echo client using streams
-----------------------------

TCP echo client using the :func:`asyncio.open_connection` function::
TCP echo client using the :func:`asyncio.connect` function::

import asyncio

async def tcp_echo_client(message):
reader, writer = await asyncio.open_connection(
'127.0.0.1', 8888)
stream = await asyncio.connect('127.0.0.1', 8888)
Comment thread
tirkarthi marked this conversation as resolved.
Outdated

print(f'Send: {message!r}')
writer.write(message.encode())
stream.write(message.encode())
Comment thread
tirkarthi marked this conversation as resolved.
Outdated

data = await reader.read(100)
data = await stream.read(100)
print(f'Received: {data.decode()!r}')

print('Close the connection')
writer.close()
await stream.close()

asyncio.run(tcp_echo_client('Hello World!'))

Expand All @@ -397,28 +395,28 @@ TCP echo client using the :func:`asyncio.open_connection` function::
TCP echo server using streams
-----------------------------

TCP echo server using the :func:`asyncio.start_server` function::
TCP echo server using the :class:`asyncio.StreamServer` class::

import asyncio

async def handle_echo(reader, writer):
data = await reader.read(100)
async def handle_echo(stream):
data = await stream.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
addr = stream.get_extra_info('peername')

print(f"Received {message!r} from {addr!r}")

print(f"Send: {message!r}")
writer.write(data)
await writer.drain()
stream.write(data)
Comment thread
tirkarthi marked this conversation as resolved.
Outdated
await stream.drain()

print("Close the connection")
writer.close()
await stream.close()

async def main():
Comment thread
tirkarthi marked this conversation as resolved.
server = await asyncio.start_server(
handle_echo, '127.0.0.1', 8888)
server = asyncio.StreamServer(handle_echo, '127.0.0.1', 8888)

await server.start_serving()
addr = server.sockets[0].getsockname()
print(f'Serving on {addr}')

Expand Down Expand Up @@ -446,21 +444,19 @@ Simple example querying HTTP headers of the URL passed on the command line::
async def print_http_headers(url):
url = urllib.parse.urlsplit(url)
if url.scheme == 'https':
reader, writer = await asyncio.open_connection(
url.hostname, 443, ssl=True)
stream = await asyncio.connect(url.hostname, 443, ssl=True)
else:
reader, writer = await asyncio.open_connection(
url.hostname, 80)
stream = await asyncio.connect(url.hostname, 80)

query = (
f"HEAD {url.path or '/'} HTTP/1.0\r\n"
f"Host: {url.hostname}\r\n"
f"\r\n"
)

writer.write(query.encode('latin-1'))
stream.write(query.encode('latin-1'))
Comment thread
tirkarthi marked this conversation as resolved.
while True:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some PEP 572 related example.

while True:
    line = await stream.readline()
    if not line:
        break

    line = line.decode('latin1').rstrip()
    if line:
        print(f'HTTP header> {line}')
while (line := await stream.readline()):
    line = line.decode('latin1').rstrip()
    if line:
        print(f'HTTP header> {line}')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm. Agree, := provides better readable code. Please apply.

line = await reader.readline()
line = await stream.readline()
if not line:
break

Expand All @@ -469,7 +465,7 @@ Simple example querying HTTP headers of the URL passed on the command line::
print(f'HTTP header> {line}')

# Ignore the body, close the socket
writer.close()
await stream.close()

url = sys.argv[1]
asyncio.run(print_http_headers(url))
Expand All @@ -490,7 +486,7 @@ Register an open socket to wait for data using streams
------------------------------------------------------

Coroutine waiting until a socket receives data using the
:func:`open_connection` function::
:func:`asyncio.connect` function::

import asyncio
import socket
Expand All @@ -504,17 +500,17 @@ Coroutine waiting until a socket receives data using the
rsock, wsock = socket.socketpair()

# Register the open socket to wait for data.
reader, writer = await asyncio.open_connection(sock=rsock)
stream = await asyncio.connect(sock=rsock)

# Simulate the reception of data from the network
loop.call_soon(wsock.send, 'abc'.encode())

# Wait for data
data = await reader.read(100)
data = await stream.read(100)

# Got data, we are done: close the socket
print("Received:", data.decode())
writer.close()
await stream.close()

# Close the second socket
wsock.close()
Expand Down