blob: b76ed379c7f4c88d5bbeefd10c1b28cb590689b9 [file] [log] [blame]
Victor Stinner24f8ebf2014-01-23 11:05:01 +01001.. currentmodule:: asyncio
2
Victor Stinner9592edb2014-02-02 15:03:02 +01003.. _asyncio-streams:
Victor Stinner4b4f9eb2014-01-24 17:33:20 +01004
Yury Selivanov7c7605f2018-09-11 09:54:40 -07005=======
6Streams
7=======
Victor Stinner24f8ebf2014-01-23 11:05:01 +01008
Kyle Stanleyf9000642019-10-10 19:18:46 -04009**Source code:** :source:`Lib/asyncio/streams.py`
10
11-------------------------------------------------
12
Yury Selivanov7c7605f2018-09-11 09:54:40 -070013Streams are high-level async/await-ready primitives to work with
Yury Selivanov8be876e2018-09-11 17:10:37 -070014network connections. Streams allow sending and receiving data without
Yury Selivanov7c7605f2018-09-11 09:54:40 -070015using callbacks or low-level protocols and transports.
lf627d2c82017-07-25 17:03:51 -060016
Yury Selivanov7372c3b2018-09-14 15:11:24 -070017.. _asyncio_example_stream:
18
Yury Selivanov8be876e2018-09-11 17:10:37 -070019Here is an example of a TCP echo client written using asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -070020streams::
Victor Stinner24f8ebf2014-01-23 11:05:01 +010021
Yury Selivanov7c7605f2018-09-11 09:54:40 -070022 import asyncio
Guido van Rossum19ff6972015-10-19 13:18:04 -070023
Yury Selivanov7c7605f2018-09-11 09:54:40 -070024 async def tcp_echo_client(message):
Yury Selivanov6758e6e2019-09-29 21:59:55 -070025 reader, writer = await asyncio.open_connection(
26 '127.0.0.1', 8888)
Yury Selivanov7c7605f2018-09-11 09:54:40 -070027
Yury Selivanov6758e6e2019-09-29 21:59:55 -070028 print(f'Send: {message!r}')
29 writer.write(message.encode())
30 await writer.drain()
31
32 data = await reader.read(100)
33 print(f'Received: {data.decode()!r}')
34
35 print('Close the connection')
36 writer.close()
37 await writer.wait_closed()
Yury Selivanov7c7605f2018-09-11 09:54:40 -070038
39 asyncio.run(tcp_echo_client('Hello World!'))
Guido van Rossum19ff6972015-10-19 13:18:04 -070040
41
Yury Selivanov8be876e2018-09-11 17:10:37 -070042See also the `Examples`_ section below.
43
44
Yury Selivanov7c7605f2018-09-11 09:54:40 -070045.. rubric:: Stream Functions
Victor Stinner24f8ebf2014-01-23 11:05:01 +010046
Yury Selivanov7c7605f2018-09-11 09:54:40 -070047The following top-level asyncio functions can be used to create
48and work with streams:
Victor Stinner24f8ebf2014-01-23 11:05:01 +010049
Victor Stinner24f8ebf2014-01-23 11:05:01 +010050
Yury Selivanov7c7605f2018-09-11 09:54:40 -070051.. coroutinefunction:: open_connection(host=None, port=None, \*, \
52 loop=None, limit=None, ssl=None, family=0, \
53 proto=0, flags=0, sock=None, local_addr=None, \
54 server_hostname=None, ssl_handshake_timeout=None)
55
56 Establish a network connection and return a pair of
Yury Selivanov8be876e2018-09-11 17:10:37 -070057 ``(reader, writer)`` objects.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070058
59 The returned *reader* and *writer* objects are instances of
60 :class:`StreamReader` and :class:`StreamWriter` classes.
61
62 The *loop* argument is optional and can always be determined
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040063 automatically when this function is awaited from a coroutine.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070064
65 *limit* determines the buffer size limit used by the
Yury Selivanov8be876e2018-09-11 17:10:37 -070066 returned :class:`StreamReader` instance. By default the *limit*
67 is set to 64 KiB.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010068
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040069 The rest of the arguments are passed directly to
Yury Selivanov7c7605f2018-09-11 09:54:40 -070070 :meth:`loop.create_connection`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010071
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040072 .. versionadded:: 3.7
73
74 The *ssl_handshake_timeout* parameter.
75
Yury Selivanov7c7605f2018-09-11 09:54:40 -070076.. coroutinefunction:: start_server(client_connected_cb, host=None, \
Yury Selivanov6758e6e2019-09-29 21:59:55 -070077 port=None, \*, loop=None, limit=None, \
Yury Selivanov7c7605f2018-09-11 09:54:40 -070078 family=socket.AF_UNSPEC, \
79 flags=socket.AI_PASSIVE, sock=None, \
80 backlog=100, ssl=None, reuse_address=None, \
81 reuse_port=None, ssl_handshake_timeout=None, \
82 start_serving=True)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010083
Yury Selivanov7c7605f2018-09-11 09:54:40 -070084 Start a socket server.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010085
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040086 The *client_connected_cb* callback is called whenever a new client
Yury Selivanov7c7605f2018-09-11 09:54:40 -070087 connection is established. It receives a ``(reader, writer)`` pair
88 as two arguments, instances of the :class:`StreamReader` and
89 :class:`StreamWriter` classes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010090
Yury Selivanov7c7605f2018-09-11 09:54:40 -070091 *client_connected_cb* can be a plain callable or a
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040092 :ref:`coroutine function <coroutine>`; if it is a coroutine function,
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040093 it will be automatically scheduled as a :class:`Task`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010094
Yury Selivanov7c7605f2018-09-11 09:54:40 -070095 The *loop* argument is optional and can always be determined
96 automatically when this method is awaited from a coroutine.
97
98 *limit* determines the buffer size limit used by the
Yury Selivanov8be876e2018-09-11 17:10:37 -070099 returned :class:`StreamReader` instance. By default the *limit*
100 is set to 64 KiB.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400101
102 The rest of the arguments are passed directly to
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700103 :meth:`loop.create_server`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100104
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400105 .. versionadded:: 3.7
106
107 The *ssl_handshake_timeout* and *start_serving* parameters.
108
Yury Selivanov8be876e2018-09-11 17:10:37 -0700109
110.. rubric:: Unix Sockets
111
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700112.. coroutinefunction:: open_unix_connection(path=None, \*, loop=None, \
113 limit=None, ssl=None, sock=None, \
114 server_hostname=None, ssl_handshake_timeout=None)
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500115
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400116 Establish a Unix socket connection and return a pair of
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700117 ``(reader, writer)``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500118
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400119 Similar to :func:`open_connection` but operates on Unix sockets.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400120
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700121 See also the documentation of :meth:`loop.create_unix_connection`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500122
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400123 .. availability:: Unix.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500124
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400125 .. versionadded:: 3.7
126
127 The *ssl_handshake_timeout* parameter.
128
129 .. versionchanged:: 3.7
130
131 The *path* parameter can now be a :term:`path-like object`
132
Yury Selivanov8be876e2018-09-11 17:10:37 -0700133
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700134.. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \
135 \*, loop=None, limit=None, sock=None, \
136 backlog=100, ssl=None, ssl_handshake_timeout=None, \
137 start_serving=True)
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500138
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400139 Start a Unix socket server.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500140
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400141 Similar to :func:`start_server` but works with Unix sockets.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400142
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700143 See also the documentation of :meth:`loop.create_unix_server`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500144
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400145 .. availability:: Unix.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500146
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400147 .. versionadded:: 3.7
148
149 The *ssl_handshake_timeout* and *start_serving* parameters.
150
151 .. versionchanged:: 3.7
152
153 The *path* parameter can now be a :term:`path-like object`.
154
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700155
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100156StreamReader
157============
158
Yury Selivanov8be876e2018-09-11 17:10:37 -0700159.. class:: StreamReader
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100160
Yury Selivanov8be876e2018-09-11 17:10:37 -0700161 Represents a reader object that provides APIs to read data
162 from the IO stream.
Victor Stinner83704962015-02-25 14:24:15 +0100163
Yury Selivanov8be876e2018-09-11 17:10:37 -0700164 It is not recommended to instantiate *StreamReader* objects
165 directly; use :func:`open_connection` and :func:`start_server`
166 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100167
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100168 .. coroutinemethod:: read(n=-1)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100169
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500170 Read up to *n* bytes. If *n* is not provided, or set to ``-1``,
171 read until EOF and return all read bytes.
172
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400173 If EOF was received and the internal buffer is empty,
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500174 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100175
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100176 .. coroutinemethod:: readline()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100177
Yury Selivanov8be876e2018-09-11 17:10:37 -0700178 Read one line, where "line" is a sequence of bytes
179 ending with ``\n``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500180
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400181 If EOF is received and ``\n`` was not found, the method
Yury Selivanov8be876e2018-09-11 17:10:37 -0700182 returns partially read data.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500183
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400184 If EOF is received and the internal buffer is empty,
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500185 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100186
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100187 .. coroutinemethod:: readexactly(n)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100188
Yury Selivanov8be876e2018-09-11 17:10:37 -0700189 Read exactly *n* bytes.
190
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400191 Raise an :exc:`IncompleteReadError` if EOF is reached before *n*
Yury Selivanov8be876e2018-09-11 17:10:37 -0700192 can be read. Use the :attr:`IncompleteReadError.partial`
193 attribute to get the partially read data.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100194
Berker Peksage5b0bd12016-10-18 00:34:46 +0300195 .. coroutinemethod:: readuntil(separator=b'\\n')
Yury Selivanov950204d2016-05-16 16:23:00 -0400196
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400197 Read data from the stream until *separator* is found.
Yury Selivanov950204d2016-05-16 16:23:00 -0400198
199 On success, the data and separator will be removed from the
200 internal buffer (consumed). Returned data will include the
201 separator at the end.
202
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400203 If the amount of data read exceeds the configured stream limit, a
204 :exc:`LimitOverrunError` exception is raised, and the data
205 is left in the internal buffer and can be read again.
Yury Selivanov950204d2016-05-16 16:23:00 -0400206
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400207 If EOF is reached before the complete separator is found,
208 an :exc:`IncompleteReadError` exception is raised, and the internal
209 buffer is reset. The :attr:`IncompleteReadError.partial` attribute
210 may contain a portion of the separator.
Yury Selivanov950204d2016-05-16 16:23:00 -0400211
212 .. versionadded:: 3.5.2
213
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500214 .. method:: at_eof()
215
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700216 Return ``True`` if the buffer is empty and :meth:`feed_eof`
217 was called.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500218
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100219
220StreamWriter
221============
222
Yury Selivanov8be876e2018-09-11 17:10:37 -0700223.. class:: StreamWriter
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100224
Yury Selivanov8be876e2018-09-11 17:10:37 -0700225 Represents a writer object that provides APIs to write data
226 to the IO stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100227
Yury Selivanov8be876e2018-09-11 17:10:37 -0700228 It is not recommended to instantiate *StreamWriter* objects
229 directly; use :func:`open_connection` and :func:`start_server`
230 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100231
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400232 .. method:: write(data)
Andrew Svetlov11194c82018-09-13 16:53:49 -0700233
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400234 The method attempts to write the *data* to the underlying socket immediately.
235 If that fails, the data is queued in an internal write buffer until it can be
236 sent.
Andrew Svetlov11194c82018-09-13 16:53:49 -0700237
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700238 The method should be used along with the ``drain()`` method::
Andrew Svetlov11194c82018-09-13 16:53:49 -0700239
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400240 stream.write(data)
241 await stream.drain()
Andrew Svetlov11194c82018-09-13 16:53:49 -0700242
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400243 .. method:: writelines(data)
244
245 The method writes a list (or any iterable) of bytes to the underlying socket
246 immediately.
247 If that fails, the data is queued in an internal write buffer until it can be
248 sent.
249
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700250 The method should be used along with the ``drain()`` method::
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400251
252 stream.writelines(lines)
253 await stream.drain()
254
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400255 .. method:: close()
256
257 The method closes the stream and the underlying socket.
258
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700259 The method should be used along with the ``wait_closed()`` method::
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400260
261 stream.close()
262 await stream.wait_closed()
263
Andrew Svetlov11194c82018-09-13 16:53:49 -0700264 .. method:: can_write_eof()
265
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200266 Return ``True`` if the underlying transport supports
267 the :meth:`write_eof` method, ``False`` otherwise.
Andrew Svetlov11194c82018-09-13 16:53:49 -0700268
269 .. method:: write_eof()
270
271 Close the write end of the stream after the buffered write
272 data is flushed.
273
274 .. attribute:: transport
275
276 Return the underlying asyncio transport.
277
278 .. method:: get_extra_info(name, default=None)
279
280 Access optional transport information; see
281 :meth:`BaseTransport.get_extra_info` for details.
282
Yury Selivanov8be876e2018-09-11 17:10:37 -0700283 .. coroutinemethod:: drain()
284
285 Wait until it is appropriate to resume writing to the stream.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400286 Example::
Yury Selivanov8be876e2018-09-11 17:10:37 -0700287
288 writer.write(data)
289 await writer.drain()
290
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400291 This is a flow control method that interacts with the underlying
Yury Selivanov8be876e2018-09-11 17:10:37 -0700292 IO write buffer. When the size of the buffer reaches
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400293 the high watermark, *drain()* blocks until the size of the
294 buffer is drained down to the low watermark and writing can
Yury Selivanov8be876e2018-09-11 17:10:37 -0700295 be resumed. When there is nothing to wait for, the :meth:`drain`
296 returns immediately.
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100297
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200298 .. method:: is_closing()
299
Yury Selivanov8be876e2018-09-11 17:10:37 -0700300 Return ``True`` if the stream is closed or in the process of
301 being closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200302
303 .. versionadded:: 3.7
304
305 .. coroutinemethod:: wait_closed()
306
Yury Selivanov8be876e2018-09-11 17:10:37 -0700307 Wait until the stream is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200308
Yury Selivanov8be876e2018-09-11 17:10:37 -0700309 Should be called after :meth:`close` to wait until the underlying
310 connection is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200311
312 .. versionadded:: 3.7
313
Victor Stinnerc520edc2014-01-23 11:25:48 +0100314
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700315Examples
316========
Victor Stinner5121a9b2014-10-11 15:52:14 +0200317
Victor Stinnered051592014-10-12 20:18:16 +0200318.. _asyncio-tcp-echo-client-streams:
319
320TCP echo client using streams
321-----------------------------
322
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700323TCP echo client using the :func:`asyncio.open_connection` function::
Victor Stinnered051592014-10-12 20:18:16 +0200324
325 import asyncio
326
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700327 async def tcp_echo_client(message):
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700328 reader, writer = await asyncio.open_connection(
329 '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200330
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700331 print(f'Send: {message!r}')
332 writer.write(message.encode())
333
334 data = await reader.read(100)
335 print(f'Received: {data.decode()!r}')
336
337 print('Close the connection')
338 writer.close()
Victor Stinnered051592014-10-12 20:18:16 +0200339
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700340 asyncio.run(tcp_echo_client('Hello World!'))
341
Victor Stinnered051592014-10-12 20:18:16 +0200342
343.. seealso::
344
Yury Selivanov394374e2018-09-17 15:35:24 -0400345 The :ref:`TCP echo client protocol <asyncio_example_tcp_echo_client_protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700346 example uses the low-level :meth:`loop.create_connection` method.
Victor Stinnered051592014-10-12 20:18:16 +0200347
348
349.. _asyncio-tcp-echo-server-streams:
350
351TCP echo server using streams
352-----------------------------
353
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700354TCP echo server using the :func:`asyncio.start_server` function::
Victor Stinnered051592014-10-12 20:18:16 +0200355
356 import asyncio
357
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700358 async def handle_echo(reader, writer):
359 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200360 message = data.decode()
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700361 addr = writer.get_extra_info('peername')
Victor Stinnered051592014-10-12 20:18:16 +0200362
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700363 print(f"Received {message!r} from {addr!r}")
364
365 print(f"Send: {message!r}")
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700366 writer.write(data)
367 await writer.drain()
Victor Stinnered051592014-10-12 20:18:16 +0200368
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700369 print("Close the connection")
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700370 writer.close()
Victor Stinnered051592014-10-12 20:18:16 +0200371
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700372 async def main():
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700373 server = await asyncio.start_server(
374 handle_echo, '127.0.0.1', 8888)
375
376 addr = server.sockets[0].getsockname()
377 print(f'Serving on {addr}')
378
379 async with server:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700380 await server.serve_forever()
381
382 asyncio.run(main())
383
Victor Stinnered051592014-10-12 20:18:16 +0200384
385.. seealso::
386
Yury Selivanov394374e2018-09-17 15:35:24 -0400387 The :ref:`TCP echo server protocol <asyncio_example_tcp_echo_server_protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700388 example uses the :meth:`loop.create_server` method.
Victor Stinnered051592014-10-12 20:18:16 +0200389
390
Victor Stinner5121a9b2014-10-11 15:52:14 +0200391Get HTTP headers
392----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100393
394Simple example querying HTTP headers of the URL passed on the command line::
395
396 import asyncio
397 import urllib.parse
398 import sys
399
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400400 async def print_http_headers(url):
Victor Stinnerc520edc2014-01-23 11:25:48 +0100401 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200402 if url.scheme == 'https':
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700403 reader, writer = await asyncio.open_connection(
404 url.hostname, 443, ssl=True)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200405 else:
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700406 reader, writer = await asyncio.open_connection(
407 url.hostname, 80)
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700408
409 query = (
410 f"HEAD {url.path or '/'} HTTP/1.0\r\n"
411 f"Host: {url.hostname}\r\n"
412 f"\r\n"
413 )
414
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700415 writer.write(query.encode('latin-1'))
416 while True:
417 line = await reader.readline()
418 if not line:
419 break
420
Victor Stinnerc520edc2014-01-23 11:25:48 +0100421 line = line.decode('latin1').rstrip()
422 if line:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700423 print(f'HTTP header> {line}')
Victor Stinnerc520edc2014-01-23 11:25:48 +0100424
Victor Stinner5121a9b2014-10-11 15:52:14 +0200425 # Ignore the body, close the socket
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700426 writer.close()
Victor Stinner5121a9b2014-10-11 15:52:14 +0200427
Victor Stinnerc520edc2014-01-23 11:25:48 +0100428 url = sys.argv[1]
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700429 asyncio.run(print_http_headers(url))
430
Victor Stinnerc520edc2014-01-23 11:25:48 +0100431
432Usage::
433
434 python example.py http://example.com/path/page.html
435
Victor Stinner04e6df32014-10-11 16:16:27 +0200436or with HTTPS::
437
438 python example.py https://example.com/path/page.html
439
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700440
Yury Selivanov394374e2018-09-17 15:35:24 -0400441.. _asyncio_example_create_connection-streams:
Victor Stinner04e6df32014-10-11 16:16:27 +0200442
443Register an open socket to wait for data using streams
444------------------------------------------------------
445
446Coroutine waiting until a socket receives data using the
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700447:func:`open_connection` function::
Victor Stinner04e6df32014-10-11 16:16:27 +0200448
449 import asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700450 import socket
Victor Stinner04e6df32014-10-11 16:16:27 +0200451
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700452 async def wait_for_data():
453 # Get a reference to the current event loop because
454 # we want to access low-level APIs.
455 loop = asyncio.get_running_loop()
Victor Stinner04e6df32014-10-11 16:16:27 +0200456
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700457 # Create a pair of connected sockets.
458 rsock, wsock = socket.socketpair()
459
460 # Register the open socket to wait for data.
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700461 reader, writer = await asyncio.open_connection(sock=rsock)
Victor Stinner04e6df32014-10-11 16:16:27 +0200462
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700463 # Simulate the reception of data from the network
464 loop.call_soon(wsock.send, 'abc'.encode())
Victor Stinner04e6df32014-10-11 16:16:27 +0200465
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700466 # Wait for data
467 data = await reader.read(100)
468
469 # Got data, we are done: close the socket
470 print("Received:", data.decode())
471 writer.close()
Victor Stinner04e6df32014-10-11 16:16:27 +0200472
473 # Close the second socket
474 wsock.close()
475
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700476 asyncio.run(wait_for_data())
Victor Stinner04e6df32014-10-11 16:16:27 +0200477
478.. seealso::
479
480 The :ref:`register an open socket to wait for data using a protocol
Yury Selivanov394374e2018-09-17 15:35:24 -0400481 <asyncio_example_create_connection>` example uses a low-level protocol and
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700482 the :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200483
484 The :ref:`watch a file descriptor for read events
Yury Selivanov394374e2018-09-17 15:35:24 -0400485 <asyncio_example_watch_fd>` example uses the low-level
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700486 :meth:`loop.add_reader` method to watch a file descriptor.