blob: 471e6e9099c2c4bc89cd99b3e1130049530ef96a [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
Yury Selivanov7c7605f2018-09-11 09:54:40 -07009Streams are high-level async/await-ready primitives to work with
Yury Selivanov8be876e2018-09-11 17:10:37 -070010network connections. Streams allow sending and receiving data without
Yury Selivanov7c7605f2018-09-11 09:54:40 -070011using callbacks or low-level protocols and transports.
lf627d2c82017-07-25 17:03:51 -060012
Yury Selivanov7372c3b2018-09-14 15:11:24 -070013.. _asyncio_example_stream:
14
Yury Selivanov8be876e2018-09-11 17:10:37 -070015Here is an example of a TCP echo client written using asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -070016streams::
Victor Stinner24f8ebf2014-01-23 11:05:01 +010017
Yury Selivanov7c7605f2018-09-11 09:54:40 -070018 import asyncio
Guido van Rossum19ff6972015-10-19 13:18:04 -070019
Yury Selivanov7c7605f2018-09-11 09:54:40 -070020 async def tcp_echo_client(message):
Yury Selivanov6758e6e2019-09-29 21:59:55 -070021 reader, writer = await asyncio.open_connection(
22 '127.0.0.1', 8888)
Yury Selivanov7c7605f2018-09-11 09:54:40 -070023
Yury Selivanov6758e6e2019-09-29 21:59:55 -070024 print(f'Send: {message!r}')
25 writer.write(message.encode())
26 await writer.drain()
27
28 data = await reader.read(100)
29 print(f'Received: {data.decode()!r}')
30
31 print('Close the connection')
32 writer.close()
33 await writer.wait_closed()
Yury Selivanov7c7605f2018-09-11 09:54:40 -070034
35 asyncio.run(tcp_echo_client('Hello World!'))
Guido van Rossum19ff6972015-10-19 13:18:04 -070036
37
Yury Selivanov8be876e2018-09-11 17:10:37 -070038See also the `Examples`_ section below.
39
40
Yury Selivanov7c7605f2018-09-11 09:54:40 -070041.. rubric:: Stream Functions
Victor Stinner24f8ebf2014-01-23 11:05:01 +010042
Yury Selivanov7c7605f2018-09-11 09:54:40 -070043The following top-level asyncio functions can be used to create
44and work with streams:
Victor Stinner24f8ebf2014-01-23 11:05:01 +010045
Victor Stinner24f8ebf2014-01-23 11:05:01 +010046
Yury Selivanov7c7605f2018-09-11 09:54:40 -070047.. coroutinefunction:: open_connection(host=None, port=None, \*, \
48 loop=None, limit=None, ssl=None, family=0, \
49 proto=0, flags=0, sock=None, local_addr=None, \
50 server_hostname=None, ssl_handshake_timeout=None)
51
52 Establish a network connection and return a pair of
Yury Selivanov8be876e2018-09-11 17:10:37 -070053 ``(reader, writer)`` objects.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070054
55 The returned *reader* and *writer* objects are instances of
56 :class:`StreamReader` and :class:`StreamWriter` classes.
57
58 The *loop* argument is optional and can always be determined
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040059 automatically when this function is awaited from a coroutine.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070060
61 *limit* determines the buffer size limit used by the
Yury Selivanov8be876e2018-09-11 17:10:37 -070062 returned :class:`StreamReader` instance. By default the *limit*
63 is set to 64 KiB.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010064
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040065 The rest of the arguments are passed directly to
Yury Selivanov7c7605f2018-09-11 09:54:40 -070066 :meth:`loop.create_connection`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010067
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040068 .. versionadded:: 3.7
69
70 The *ssl_handshake_timeout* parameter.
71
Yury Selivanov7c7605f2018-09-11 09:54:40 -070072.. coroutinefunction:: start_server(client_connected_cb, host=None, \
Yury Selivanov6758e6e2019-09-29 21:59:55 -070073 port=None, \*, loop=None, limit=None, \
Yury Selivanov7c7605f2018-09-11 09:54:40 -070074 family=socket.AF_UNSPEC, \
75 flags=socket.AI_PASSIVE, sock=None, \
76 backlog=100, ssl=None, reuse_address=None, \
77 reuse_port=None, ssl_handshake_timeout=None, \
78 start_serving=True)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010079
Yury Selivanov7c7605f2018-09-11 09:54:40 -070080 Start a socket server.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010081
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040082 The *client_connected_cb* callback is called whenever a new client
Yury Selivanov7c7605f2018-09-11 09:54:40 -070083 connection is established. It receives a ``(reader, writer)`` pair
84 as two arguments, instances of the :class:`StreamReader` and
85 :class:`StreamWriter` classes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010086
Yury Selivanov7c7605f2018-09-11 09:54:40 -070087 *client_connected_cb* can be a plain callable or a
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040088 :ref:`coroutine function <coroutine>`; if it is a coroutine function,
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040089 it will be automatically scheduled as a :class:`Task`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010090
Yury Selivanov7c7605f2018-09-11 09:54:40 -070091 The *loop* argument is optional and can always be determined
92 automatically when this method is awaited from a coroutine.
93
94 *limit* determines the buffer size limit used by the
Yury Selivanov8be876e2018-09-11 17:10:37 -070095 returned :class:`StreamReader` instance. By default the *limit*
96 is set to 64 KiB.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -040097
98 The rest of the arguments are passed directly to
Yury Selivanov7c7605f2018-09-11 09:54:40 -070099 :meth:`loop.create_server`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100100
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400101 .. versionadded:: 3.7
102
103 The *ssl_handshake_timeout* and *start_serving* parameters.
104
Yury Selivanov8be876e2018-09-11 17:10:37 -0700105
106.. rubric:: Unix Sockets
107
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700108.. coroutinefunction:: open_unix_connection(path=None, \*, loop=None, \
109 limit=None, ssl=None, sock=None, \
110 server_hostname=None, ssl_handshake_timeout=None)
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500111
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400112 Establish a Unix socket connection and return a pair of
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700113 ``(reader, writer)``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500114
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400115 Similar to :func:`open_connection` but operates on Unix sockets.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400116
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700117 See also the documentation of :meth:`loop.create_unix_connection`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500118
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400119 .. availability:: Unix.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500120
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400121 .. versionadded:: 3.7
122
123 The *ssl_handshake_timeout* parameter.
124
125 .. versionchanged:: 3.7
126
127 The *path* parameter can now be a :term:`path-like object`
128
Yury Selivanov8be876e2018-09-11 17:10:37 -0700129
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700130.. coroutinefunction:: start_unix_server(client_connected_cb, path=None, \
131 \*, loop=None, limit=None, sock=None, \
132 backlog=100, ssl=None, ssl_handshake_timeout=None, \
133 start_serving=True)
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500134
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400135 Start a Unix socket server.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500136
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400137 Similar to :func:`start_server` but works with Unix sockets.
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400138
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700139 See also the documentation of :meth:`loop.create_unix_server`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500140
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400141 .. availability:: Unix.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500142
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400143 .. versionadded:: 3.7
144
145 The *ssl_handshake_timeout* and *start_serving* parameters.
146
147 .. versionchanged:: 3.7
148
149 The *path* parameter can now be a :term:`path-like object`.
150
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700151
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100152StreamReader
153============
154
Yury Selivanov8be876e2018-09-11 17:10:37 -0700155.. class:: StreamReader
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100156
Yury Selivanov8be876e2018-09-11 17:10:37 -0700157 Represents a reader object that provides APIs to read data
158 from the IO stream.
Victor Stinner83704962015-02-25 14:24:15 +0100159
Yury Selivanov8be876e2018-09-11 17:10:37 -0700160 It is not recommended to instantiate *StreamReader* objects
161 directly; use :func:`open_connection` and :func:`start_server`
162 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100163
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100164 .. coroutinemethod:: read(n=-1)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100165
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500166 Read up to *n* bytes. If *n* is not provided, or set to ``-1``,
167 read until EOF and return all read bytes.
168
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400169 If EOF was received and the internal buffer is empty,
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500170 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100171
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100172 .. coroutinemethod:: readline()
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100173
Yury Selivanov8be876e2018-09-11 17:10:37 -0700174 Read one line, where "line" is a sequence of bytes
175 ending with ``\n``.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500176
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400177 If EOF is received and ``\n`` was not found, the method
Yury Selivanov8be876e2018-09-11 17:10:37 -0700178 returns partially read data.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500179
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400180 If EOF is received and the internal buffer is empty,
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500181 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100182
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100183 .. coroutinemethod:: readexactly(n)
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100184
Yury Selivanov8be876e2018-09-11 17:10:37 -0700185 Read exactly *n* bytes.
186
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400187 Raise an :exc:`IncompleteReadError` if EOF is reached before *n*
Yury Selivanov8be876e2018-09-11 17:10:37 -0700188 can be read. Use the :attr:`IncompleteReadError.partial`
189 attribute to get the partially read data.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100190
Berker Peksage5b0bd12016-10-18 00:34:46 +0300191 .. coroutinemethod:: readuntil(separator=b'\\n')
Yury Selivanov950204d2016-05-16 16:23:00 -0400192
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400193 Read data from the stream until *separator* is found.
Yury Selivanov950204d2016-05-16 16:23:00 -0400194
195 On success, the data and separator will be removed from the
196 internal buffer (consumed). Returned data will include the
197 separator at the end.
198
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400199 If the amount of data read exceeds the configured stream limit, a
200 :exc:`LimitOverrunError` exception is raised, and the data
201 is left in the internal buffer and can be read again.
Yury Selivanov950204d2016-05-16 16:23:00 -0400202
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400203 If EOF is reached before the complete separator is found,
204 an :exc:`IncompleteReadError` exception is raised, and the internal
205 buffer is reset. The :attr:`IncompleteReadError.partial` attribute
206 may contain a portion of the separator.
Yury Selivanov950204d2016-05-16 16:23:00 -0400207
208 .. versionadded:: 3.5.2
209
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500210 .. method:: at_eof()
211
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700212 Return ``True`` if the buffer is empty and :meth:`feed_eof`
213 was called.
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500214
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100215
216StreamWriter
217============
218
Yury Selivanov8be876e2018-09-11 17:10:37 -0700219.. class:: StreamWriter
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100220
Yury Selivanov8be876e2018-09-11 17:10:37 -0700221 Represents a writer object that provides APIs to write data
222 to the IO stream.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100223
Yury Selivanov8be876e2018-09-11 17:10:37 -0700224 It is not recommended to instantiate *StreamWriter* objects
225 directly; use :func:`open_connection` and :func:`start_server`
226 instead.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100227
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400228 .. method:: write(data)
Andrew Svetlov11194c82018-09-13 16:53:49 -0700229
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400230 The method attempts to write the *data* to the underlying socket immediately.
231 If that fails, the data is queued in an internal write buffer until it can be
232 sent.
Andrew Svetlov11194c82018-09-13 16:53:49 -0700233
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700234 The method should be used along with the ``drain()`` method::
Andrew Svetlov11194c82018-09-13 16:53:49 -0700235
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400236 stream.write(data)
237 await stream.drain()
Andrew Svetlov11194c82018-09-13 16:53:49 -0700238
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400239 .. method:: writelines(data)
240
241 The method writes a list (or any iterable) of bytes to the underlying socket
242 immediately.
243 If that fails, the data is queued in an internal write buffer until it can be
244 sent.
245
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700246 The method should be used along with the ``drain()`` method::
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400247
248 stream.writelines(lines)
249 await stream.drain()
250
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400251 .. method:: close()
252
253 The method closes the stream and the underlying socket.
254
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700255 The method should be used along with the ``wait_closed()`` method::
Andrew Svetlova076e4f2019-05-09 15:14:58 -0400256
257 stream.close()
258 await stream.wait_closed()
259
Andrew Svetlov11194c82018-09-13 16:53:49 -0700260 .. method:: can_write_eof()
261
262 Return *True* if the underlying transport supports
263 the :meth:`write_eof` method, *False* otherwise.
264
265 .. method:: write_eof()
266
267 Close the write end of the stream after the buffered write
268 data is flushed.
269
270 .. attribute:: transport
271
272 Return the underlying asyncio transport.
273
274 .. method:: get_extra_info(name, default=None)
275
276 Access optional transport information; see
277 :meth:`BaseTransport.get_extra_info` for details.
278
Yury Selivanov8be876e2018-09-11 17:10:37 -0700279 .. coroutinemethod:: drain()
280
281 Wait until it is appropriate to resume writing to the stream.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400282 Example::
Yury Selivanov8be876e2018-09-11 17:10:37 -0700283
284 writer.write(data)
285 await writer.drain()
286
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400287 This is a flow control method that interacts with the underlying
Yury Selivanov8be876e2018-09-11 17:10:37 -0700288 IO write buffer. When the size of the buffer reaches
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400289 the high watermark, *drain()* blocks until the size of the
290 buffer is drained down to the low watermark and writing can
Yury Selivanov8be876e2018-09-11 17:10:37 -0700291 be resumed. When there is nothing to wait for, the :meth:`drain`
292 returns immediately.
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100293
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200294 .. method:: is_closing()
295
Yury Selivanov8be876e2018-09-11 17:10:37 -0700296 Return ``True`` if the stream is closed or in the process of
297 being closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200298
299 .. versionadded:: 3.7
300
301 .. coroutinemethod:: wait_closed()
302
Yury Selivanov8be876e2018-09-11 17:10:37 -0700303 Wait until the stream is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200304
Yury Selivanov8be876e2018-09-11 17:10:37 -0700305 Should be called after :meth:`close` to wait until the underlying
306 connection is closed.
Andrew Svetlovfe133aa2018-01-25 00:30:30 +0200307
308 .. versionadded:: 3.7
309
Victor Stinnerc520edc2014-01-23 11:25:48 +0100310
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700311Examples
312========
Victor Stinner5121a9b2014-10-11 15:52:14 +0200313
Victor Stinnered051592014-10-12 20:18:16 +0200314.. _asyncio-tcp-echo-client-streams:
315
316TCP echo client using streams
317-----------------------------
318
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700319TCP echo client using the :func:`asyncio.open_connection` function::
Victor Stinnered051592014-10-12 20:18:16 +0200320
321 import asyncio
322
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700323 async def tcp_echo_client(message):
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700324 reader, writer = await asyncio.open_connection(
325 '127.0.0.1', 8888)
Victor Stinnered051592014-10-12 20:18:16 +0200326
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700327 print(f'Send: {message!r}')
328 writer.write(message.encode())
329
330 data = await reader.read(100)
331 print(f'Received: {data.decode()!r}')
332
333 print('Close the connection')
334 writer.close()
Victor Stinnered051592014-10-12 20:18:16 +0200335
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700336 asyncio.run(tcp_echo_client('Hello World!'))
337
Victor Stinnered051592014-10-12 20:18:16 +0200338
339.. seealso::
340
Yury Selivanov394374e2018-09-17 15:35:24 -0400341 The :ref:`TCP echo client protocol <asyncio_example_tcp_echo_client_protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700342 example uses the low-level :meth:`loop.create_connection` method.
Victor Stinnered051592014-10-12 20:18:16 +0200343
344
345.. _asyncio-tcp-echo-server-streams:
346
347TCP echo server using streams
348-----------------------------
349
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700350TCP echo server using the :func:`asyncio.start_server` function::
Victor Stinnered051592014-10-12 20:18:16 +0200351
352 import asyncio
353
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700354 async def handle_echo(reader, writer):
355 data = await reader.read(100)
Victor Stinnered051592014-10-12 20:18:16 +0200356 message = data.decode()
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700357 addr = writer.get_extra_info('peername')
Victor Stinnered051592014-10-12 20:18:16 +0200358
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700359 print(f"Received {message!r} from {addr!r}")
360
361 print(f"Send: {message!r}")
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700362 writer.write(data)
363 await writer.drain()
Victor Stinnered051592014-10-12 20:18:16 +0200364
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700365 print("Close the connection")
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700366 writer.close()
Victor Stinnered051592014-10-12 20:18:16 +0200367
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700368 async def main():
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700369 server = await asyncio.start_server(
370 handle_echo, '127.0.0.1', 8888)
371
372 addr = server.sockets[0].getsockname()
373 print(f'Serving on {addr}')
374
375 async with server:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700376 await server.serve_forever()
377
378 asyncio.run(main())
379
Victor Stinnered051592014-10-12 20:18:16 +0200380
381.. seealso::
382
Yury Selivanov394374e2018-09-17 15:35:24 -0400383 The :ref:`TCP echo server protocol <asyncio_example_tcp_echo_server_protocol>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700384 example uses the :meth:`loop.create_server` method.
Victor Stinnered051592014-10-12 20:18:16 +0200385
386
Victor Stinner5121a9b2014-10-11 15:52:14 +0200387Get HTTP headers
388----------------
Victor Stinnerc520edc2014-01-23 11:25:48 +0100389
390Simple example querying HTTP headers of the URL passed on the command line::
391
392 import asyncio
393 import urllib.parse
394 import sys
395
Mikhail Terekhovd2ac4002018-08-07 16:29:06 -0400396 async def print_http_headers(url):
Victor Stinnerc520edc2014-01-23 11:25:48 +0100397 url = urllib.parse.urlsplit(url)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200398 if url.scheme == 'https':
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700399 reader, writer = await asyncio.open_connection(
400 url.hostname, 443, ssl=True)
Victor Stinner5121a9b2014-10-11 15:52:14 +0200401 else:
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700402 reader, writer = await asyncio.open_connection(
403 url.hostname, 80)
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700404
405 query = (
406 f"HEAD {url.path or '/'} HTTP/1.0\r\n"
407 f"Host: {url.hostname}\r\n"
408 f"\r\n"
409 )
410
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700411 writer.write(query.encode('latin-1'))
412 while True:
413 line = await reader.readline()
414 if not line:
415 break
416
Victor Stinnerc520edc2014-01-23 11:25:48 +0100417 line = line.decode('latin1').rstrip()
418 if line:
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700419 print(f'HTTP header> {line}')
Victor Stinnerc520edc2014-01-23 11:25:48 +0100420
Victor Stinner5121a9b2014-10-11 15:52:14 +0200421 # Ignore the body, close the socket
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700422 writer.close()
Victor Stinner5121a9b2014-10-11 15:52:14 +0200423
Victor Stinnerc520edc2014-01-23 11:25:48 +0100424 url = sys.argv[1]
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700425 asyncio.run(print_http_headers(url))
426
Victor Stinnerc520edc2014-01-23 11:25:48 +0100427
428Usage::
429
430 python example.py http://example.com/path/page.html
431
Victor Stinner04e6df32014-10-11 16:16:27 +0200432or with HTTPS::
433
434 python example.py https://example.com/path/page.html
435
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700436
Yury Selivanov394374e2018-09-17 15:35:24 -0400437.. _asyncio_example_create_connection-streams:
Victor Stinner04e6df32014-10-11 16:16:27 +0200438
439Register an open socket to wait for data using streams
440------------------------------------------------------
441
442Coroutine waiting until a socket receives data using the
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700443:func:`open_connection` function::
Victor Stinner04e6df32014-10-11 16:16:27 +0200444
445 import asyncio
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700446 import socket
Victor Stinner04e6df32014-10-11 16:16:27 +0200447
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700448 async def wait_for_data():
449 # Get a reference to the current event loop because
450 # we want to access low-level APIs.
451 loop = asyncio.get_running_loop()
Victor Stinner04e6df32014-10-11 16:16:27 +0200452
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700453 # Create a pair of connected sockets.
454 rsock, wsock = socket.socketpair()
455
456 # Register the open socket to wait for data.
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700457 reader, writer = await asyncio.open_connection(sock=rsock)
Victor Stinner04e6df32014-10-11 16:16:27 +0200458
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700459 # Simulate the reception of data from the network
460 loop.call_soon(wsock.send, 'abc'.encode())
Victor Stinner04e6df32014-10-11 16:16:27 +0200461
Yury Selivanov6758e6e2019-09-29 21:59:55 -0700462 # Wait for data
463 data = await reader.read(100)
464
465 # Got data, we are done: close the socket
466 print("Received:", data.decode())
467 writer.close()
Victor Stinner04e6df32014-10-11 16:16:27 +0200468
469 # Close the second socket
470 wsock.close()
471
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700472 asyncio.run(wait_for_data())
Victor Stinner04e6df32014-10-11 16:16:27 +0200473
474.. seealso::
475
476 The :ref:`register an open socket to wait for data using a protocol
Yury Selivanov394374e2018-09-17 15:35:24 -0400477 <asyncio_example_create_connection>` example uses a low-level protocol and
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700478 the :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200479
480 The :ref:`watch a file descriptor for read events
Yury Selivanov394374e2018-09-17 15:35:24 -0400481 <asyncio_example_watch_fd>` example uses the low-level
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700482 :meth:`loop.add_reader` method to watch a file descriptor.