blob: 4543af4c2e1a5887965d43c9fce0f2bdacbd8271 [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
Victor Stinner1374bd42014-01-24 15:34:19 +01005++++++++++++++++++++++++
6Streams (high-level API)
7++++++++++++++++++++++++
Victor Stinner24f8ebf2014-01-23 11:05:01 +01008
9Stream functions
10================
11
Victor Stinner08444382014-02-02 22:43:39 +010012.. function:: open_connection(host=None, port=None, \*, loop=None, limit=None, **kwds)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010013
14 A wrapper for :meth:`~BaseEventLoop.create_connection()` returning a (reader,
15 writer) pair.
16
17 The reader returned is a :class:`StreamReader` instance; the writer is
18 a :class:`StreamWriter` instance.
19
20 The arguments are all the usual arguments to
21 :meth:`BaseEventLoop.create_connection` except *protocol_factory*; most
22 common are positional host and port, with various optional keyword arguments
23 following.
24
25 Additional optional keyword arguments are *loop* (to set the event loop
26 instance to use) and *limit* (to set the buffer limit passed to the
27 :class:`StreamReader`).
28
29 (If you want to customize the :class:`StreamReader` and/or
30 :class:`StreamReaderProtocol` classes, just copy the code -- there's really
31 nothing special here except some convenience.)
32
Yury Selivanov37f15bc2014-02-20 16:20:44 -050033 This function is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010034
Victor Stinner08444382014-02-02 22:43:39 +010035.. function:: start_server(client_connected_cb, host=None, port=None, \*, loop=None, limit=None, **kwds)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010036
Yury Selivanovd3f8e302014-02-20 14:10:02 -050037 Start a socket server, with a callback for each client connected.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010038
39 The first parameter, *client_connected_cb*, takes two parameters:
40 *client_reader*, *client_writer*. *client_reader* is a
41 :class:`StreamReader` object, while *client_writer* is a
42 :class:`StreamWriter` object. This parameter can either be a plain callback
43 function or a :ref:`coroutine function <coroutine>`; if it is a coroutine
44 function, it will be automatically converted into a :class:`Task`.
45
46 The rest of the arguments are all the usual arguments to
47 :meth:`~BaseEventLoop.create_server()` except *protocol_factory*; most
48 common are positional host and port, with various optional keyword arguments
49 following. The return value is the same as
50 :meth:`~BaseEventLoop.create_server()`.
51
52 Additional optional keyword arguments are *loop* (to set the event loop
53 instance to use) and *limit* (to set the buffer limit passed to the
54 :class:`StreamReader`).
55
56 The return value is the same as :meth:`~BaseEventLoop.create_server()`, i.e.
57 a :class:`AbstractServer` object which can be used to stop the service.
58
Yury Selivanov37f15bc2014-02-20 16:20:44 -050059 This function is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010060
Yury Selivanovd3f8e302014-02-20 14:10:02 -050061.. function:: open_unix_connection(path=None, \*, loop=None, limit=None, **kwds)
62
63 A wrapper for :meth:`~BaseEventLoop.create_unix_connection()` returning
64 a (reader, writer) pair.
65
66 See :func:`open_connection` for information about return value and other
67 details.
68
Yury Selivanov37f15bc2014-02-20 16:20:44 -050069 This function is a :ref:`coroutine <coroutine>`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -050070
71 Availability: UNIX.
72
73.. function:: start_unix_server(client_connected_cb, path=None, \*, loop=None, limit=None, **kwds)
74
75 Start a UNIX Domain Socket server, with a callback for each client connected.
76
77 See :func:`start_server` for information about return value and other
78 details.
79
Yury Selivanov37f15bc2014-02-20 16:20:44 -050080 This function is a :ref:`coroutine <coroutine>`.
Yury Selivanovd3f8e302014-02-20 14:10:02 -050081
82 Availability: UNIX.
83
Victor Stinner24f8ebf2014-01-23 11:05:01 +010084
85StreamReader
86============
87
Victor Stinner08444382014-02-02 22:43:39 +010088.. class:: StreamReader(limit=None, loop=None)
Victor Stinner24f8ebf2014-01-23 11:05:01 +010089
90 .. method:: exception()
91
92 Get the exception.
93
94 .. method:: feed_eof()
95
Yury Selivanovd3f8e302014-02-20 14:10:02 -050096 Acknowledge the EOF.
Victor Stinner24f8ebf2014-01-23 11:05:01 +010097
98 .. method:: feed_data(data)
99
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500100 Feed *data* bytes in the internal buffer. Any operations waiting
101 for the data will be resumed.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100102
103 .. method:: set_exception(exc)
104
105 Set the exception.
106
107 .. method:: set_transport(transport)
108
109 Set the transport.
110
111 .. method:: read(n=-1)
112
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500113 Read up to *n* bytes. If *n* is not provided, or set to ``-1``,
114 read until EOF and return all read bytes.
115
116 If the EOF was received and the internal buffer is empty,
117 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100118
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500119 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100120
121 .. method:: readline()
122
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500123 Read one line, where "line" is a sequence of bytes ending with ``\n``.
124
125 If EOF is received, and ``\n`` was not found, the method will
126 return the partial read bytes.
127
128 If the EOF was received and the internal buffer is empty,
129 return an empty ``bytes`` object.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100130
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500131 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100132
133 .. method:: readexactly(n)
134
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100135 Read exactly *n* bytes. Raise an :exc:`IncompleteReadError` if the end of
136 the stream is reached before *n* can be read, the
137 :attr:`IncompleteReadError.partial` attribute of the exception contains
138 the partial read bytes.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100139
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500140 This method is a :ref:`coroutine <coroutine>`.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100141
Yury Selivanovd3f8e302014-02-20 14:10:02 -0500142 .. method:: at_eof()
143
144 Return ``True`` if the buffer is empty and :meth:`feed_eof` was called.
145
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100146
147StreamWriter
148============
149
150.. class:: StreamWriter(transport, protocol, reader, loop)
151
152 Wraps a Transport.
153
154 This exposes :meth:`write`, :meth:`writelines`, :meth:`can_write_eof()`,
155 :meth:`write_eof`, :meth:`get_extra_info` and :meth:`close`. It adds
156 :meth:`drain` which returns an optional :class:`Future` on which you can
157 wait for flow control. It also adds a transport attribute which references
158 the :class:`Transport` directly.
159
160 .. attribute:: transport
161
162 Transport.
163
Victor Stinnerffbe3c62014-02-08 22:50:07 +0100164 .. method:: can_write_eof()
165
166 Return :const:`True` if the transport supports :meth:`write_eof`,
167 :const:`False` if not. See :meth:`WriteTransport.can_write_eof`.
168
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100169 .. method:: close()
170
171 Close the transport: see :meth:`BaseTransport.close`.
172
173 .. method:: drain()
174
Victor Stinner62f8ecc2014-01-24 18:47:26 +0100175 Wait until the write buffer of the underlying transport is flushed.
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100176
Victor Stinner62f8ecc2014-01-24 18:47:26 +0100177 This method has an unusual return value. The intended use is to write::
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100178
179 w.write(data)
180 yield from w.drain()
181
182 When there's nothing to wait for, :meth:`drain()` returns ``()``, and the
183 yield-from continues immediately. When the transport buffer is full (the
184 protocol is paused), :meth:`drain` creates and returns a
185 :class:`Future` and the yield-from will block until
186 that Future is completed, which will happen when the buffer is
187 (partially) drained and the protocol is resumed.
188
189 .. method:: get_extra_info(name, default=None)
190
191 Return optional transport information: see
192 :meth:`BaseTransport.get_extra_info`.
193
194 .. method:: write(data)
195
196 Write some *data* bytes to the transport: see
197 :meth:`WriteTransport.write`.
198
199 .. method:: writelines(data)
200
201 Write a list (or any iterable) of data bytes to the transport:
202 see :meth:`WriteTransport.writelines`.
203
Victor Stinner24f8ebf2014-01-23 11:05:01 +0100204 .. method:: write_eof()
205
206 Close the write end of the transport after flushing buffered data:
207 see :meth:`WriteTransport.write_eof`.
208
209
210StreamReaderProtocol
211====================
212
213.. class:: StreamReaderProtocol(stream_reader, client_connected_cb=None, loop=None)
214
215 Trivial helper class to adapt between :class:`Protocol` and
216 :class:`StreamReader`. Sublclass of :class:`Protocol`.
217
218 *stream_reader* is a :class:`StreamReader` instance, *client_connected_cb*
219 is an optional function called with (stream_reader, stream_writer) when a
220 connection is made, *loop* is the event loop instance to use.
221
222 (This is a helper class instead of making :class:`StreamReader` itself a
223 :class:`Protocol` subclass, because the :class:`StreamReader` has other
224 potential uses, and to prevent the user of the :class:`StreamReader` to
225 accidentally call inappropriate methods of the protocol.)
226
Victor Stinnerc520edc2014-01-23 11:25:48 +0100227
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100228IncompleteReadError
229===================
230
231.. exception:: IncompleteReadError
232
Victor Stinner32970b82014-01-27 12:18:49 +0100233 Incomplete read error, subclass of :exc:`EOFError`.
Victor Stinnerb7f19ff2014-01-27 11:58:49 +0100234
235 .. attribute:: expected
236
237 Total number of expected bytes (:class:`int`).
238
239 .. attribute:: partial
240
241 Read bytes string before the end of stream was reached (:class:`bytes`).
242
243
Victor Stinnerc520edc2014-01-23 11:25:48 +0100244Example
245=======
246
247Simple example querying HTTP headers of the URL passed on the command line::
248
249 import asyncio
250 import urllib.parse
251 import sys
252
253 @asyncio.coroutine
254 def print_http_headers(url):
255 url = urllib.parse.urlsplit(url)
256 reader, writer = yield from asyncio.open_connection(url.hostname, 80)
257 query = ('HEAD {url.path} HTTP/1.0\r\n'
258 'Host: {url.hostname}\r\n'
259 '\r\n').format(url=url)
260 writer.write(query.encode('latin-1'))
261 while True:
262 line = yield from reader.readline()
263 if not line:
264 break
265 line = line.decode('latin1').rstrip()
266 if line:
267 print('HTTP header> %s' % line)
268
269 url = sys.argv[1]
270 loop = asyncio.get_event_loop()
271 task = asyncio.async(print_http_headers(url))
272 loop.run_until_complete(task)
Victor Stinnerf40c6632014-01-28 23:32:40 +0100273 loop.close()
Victor Stinnerc520edc2014-01-23 11:25:48 +0100274
275Usage::
276
277 python example.py http://example.com/path/page.html
278