blob: f2a9f1268e6d3ff85a6c32fea6acc54c8a2d4e0f [file] [log] [blame]
Victor Stinner24f8ebf2014-01-23 11:05:01 +01001.. currentmodule:: asyncio
2
Victor Stinner4b4f9eb2014-01-24 17:33:20 +01003.. _streams:
4
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
12.. function:: open_connection(host=None, port=None, *, loop=None, limit=_DEFAULT_LIMIT, **kwds)
13
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
33 This function returns a :ref:`coroutine object <coroutine>`.
34
35.. function:: start_server(client_connected_cb, host=None, port=None, *, loop=None, limit=_DEFAULT_LIMIT, **kwds)
36
37 Start a socket server, call back for each client connected.
38
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
59 This function returns a :ref:`coroutine object <coroutine>`.
60
61
62StreamReader
63============
64
65.. class:: StreamReader(limit=_DEFAULT_LIMIT, loop=None)
66
67 .. method:: exception()
68
69 Get the exception.
70
71 .. method:: feed_eof()
72
73 XXX
74
75 .. method:: feed_data(data)
76
77 XXX
78
79 .. method:: set_exception(exc)
80
81 Set the exception.
82
83 .. method:: set_transport(transport)
84
85 Set the transport.
86
87 .. method:: read(n=-1)
88
89 XXX
90
91 This method returns a :ref:`coroutine object <coroutine>`.
92
93 .. method:: readline()
94
95 XXX
96
97 This method returns a :ref:`coroutine object <coroutine>`.
98
99 .. method:: readexactly(n)
100
101 XXX
102
103 This method returns a :ref:`coroutine object <coroutine>`.
104
105
106StreamWriter
107============
108
109.. class:: StreamWriter(transport, protocol, reader, loop)
110
111 Wraps a Transport.
112
113 This exposes :meth:`write`, :meth:`writelines`, :meth:`can_write_eof()`,
114 :meth:`write_eof`, :meth:`get_extra_info` and :meth:`close`. It adds
115 :meth:`drain` which returns an optional :class:`Future` on which you can
116 wait for flow control. It also adds a transport attribute which references
117 the :class:`Transport` directly.
118
119 .. attribute:: transport
120
121 Transport.
122
123 .. method:: close()
124
125 Close the transport: see :meth:`BaseTransport.close`.
126
127 .. method:: drain()
128
129 This method has an unusual return value.
130
131 The intended use is to write::
132
133 w.write(data)
134 yield from w.drain()
135
136 When there's nothing to wait for, :meth:`drain()` returns ``()``, and the
137 yield-from continues immediately. When the transport buffer is full (the
138 protocol is paused), :meth:`drain` creates and returns a
139 :class:`Future` and the yield-from will block until
140 that Future is completed, which will happen when the buffer is
141 (partially) drained and the protocol is resumed.
142
143 .. method:: get_extra_info(name, default=None)
144
145 Return optional transport information: see
146 :meth:`BaseTransport.get_extra_info`.
147
148 .. method:: write(data)
149
150 Write some *data* bytes to the transport: see
151 :meth:`WriteTransport.write`.
152
153 .. method:: writelines(data)
154
155 Write a list (or any iterable) of data bytes to the transport:
156 see :meth:`WriteTransport.writelines`.
157
158 .. method:: can_write_eof()
159
160 Return :const:`True` if the transport supports :meth:`write_eof`,
161 :const:`False` if not. See :meth:`WriteTransport.can_write_eof`.
162
163 .. method:: write_eof()
164
165 Close the write end of the transport after flushing buffered data:
166 see :meth:`WriteTransport.write_eof`.
167
168
169StreamReaderProtocol
170====================
171
172.. class:: StreamReaderProtocol(stream_reader, client_connected_cb=None, loop=None)
173
174 Trivial helper class to adapt between :class:`Protocol` and
175 :class:`StreamReader`. Sublclass of :class:`Protocol`.
176
177 *stream_reader* is a :class:`StreamReader` instance, *client_connected_cb*
178 is an optional function called with (stream_reader, stream_writer) when a
179 connection is made, *loop* is the event loop instance to use.
180
181 (This is a helper class instead of making :class:`StreamReader` itself a
182 :class:`Protocol` subclass, because the :class:`StreamReader` has other
183 potential uses, and to prevent the user of the :class:`StreamReader` to
184 accidentally call inappropriate methods of the protocol.)
185
186 .. method:: connection_made(transport)
187
188 XXX
189
190 .. method:: connection_lost(exc)
191
192 XXX
193
194 .. method:: data_received(data)
195
196 XXX
197
198 .. method:: eof_received()
199
200 XXX
201
202 .. method:: pause_writing()
203
204 XXX
205
206 .. method:: resume_writing()
207
208 XXX
209
Victor Stinnerc520edc2014-01-23 11:25:48 +0100210
211Example
212=======
213
214Simple example querying HTTP headers of the URL passed on the command line::
215
216 import asyncio
217 import urllib.parse
218 import sys
219
220 @asyncio.coroutine
221 def print_http_headers(url):
222 url = urllib.parse.urlsplit(url)
223 reader, writer = yield from asyncio.open_connection(url.hostname, 80)
224 query = ('HEAD {url.path} HTTP/1.0\r\n'
225 'Host: {url.hostname}\r\n'
226 '\r\n').format(url=url)
227 writer.write(query.encode('latin-1'))
228 while True:
229 line = yield from reader.readline()
230 if not line:
231 break
232 line = line.decode('latin1').rstrip()
233 if line:
234 print('HTTP header> %s' % line)
235
236 url = sys.argv[1]
237 loop = asyncio.get_event_loop()
238 task = asyncio.async(print_http_headers(url))
239 loop.run_until_complete(task)
240
241Usage::
242
243 python example.py http://example.com/path/page.html
244