rest25/library/asynchat.rst => rest262/library/asynchat.rst
4
5.. module:: asynchat
6   :synopsis: Support for asynchronous command/response protocols.
7.. moduleauthor:: Sam Rushing <rushing@nightmare.com>
8.. sectionauthor:: Steve Holden <sholden@holdenweb.com>
9
10
11This module builds on the :mod:`asyncore` infrastructure, simplifying
n12-asynchronous clients and servers and making it easier to handle protocols whose
n12+asynchronous clients and servers and making it easier to handle protocols
13-elements are terminated by arbitrary strings, or are of variable length.
13+whose elements are terminated by arbitrary strings, or are of variable length.
14:mod:`asynchat` defines the abstract class :class:`async_chat` that you
15subclass, providing implementations of the :meth:`collect_incoming_data` and
16:meth:`found_terminator` methods. It uses the same asynchronous loop as
n17-:mod:`asyncore`, and the two types of channel, :class:`asyncore.dispatcher` and
n17+:mod:`asyncore`, and the two types of channel, :class:`asyncore.dispatcher`
18-:class:`asynchat.async_chat`, can freely be mixed in the channel map. Typically
18+and :class:`asynchat.async_chat`, can freely be mixed in the channel map.
19-an :class:`asyncore.dispatcher` server channel generates new
19+Typically an :class:`asyncore.dispatcher` server channel generates new
20-:class:`asynchat.async_chat` channel objects as it receives incoming connection
20+:class:`asynchat.async_chat` channel objects as it receives incoming
21-requests.
21+connection requests.
22
23
24.. class:: async_chat()
25
26   This class is an abstract subclass of :class:`asyncore.dispatcher`. To make
27   practical use of the code you must subclass :class:`async_chat`, providing
n28-   meaningful :meth:`collect_incoming_data` and :meth:`found_terminator` methods.
n28+   meaningful :meth:`collect_incoming_data` and :meth:`found_terminator`
29+   methods.
29   The :class:`asyncore.dispatcher` methods can be used, although not all make
30   sense in a message/response context.
31
n32-   Like :class:`asyncore.dispatcher`, :class:`async_chat` defines a set of events
n33+   Like :class:`asyncore.dispatcher`, :class:`async_chat` defines a set of
33-   that are generated by an analysis of socket conditions after a :cfunc:`select`
34+   events that are generated by an analysis of socket conditions after a
34-   call. Once the polling loop has been started the :class:`async_chat` object's
35+   :cfunc:`select` call. Once the polling loop has been started the
35-   methods are called by the event-processing framework with no action on the part
36+   :class:`async_chat` object's methods are called by the event-processing
36-   of the programmer.
37+   framework with no action on the part of the programmer.
37
n39+   Two class attributes can be modified, to improve performance, or possibly
40+   even to conserve memory.
41+ 
42+ 
43+   .. data:: ac_in_buffer_size
44+ 
45+      The asynchronous input buffer size (default ``4096``).
46+ 
47+ 
48+   .. data:: ac_out_buffer_size
49+ 
50+      The asynchronous output buffer size (default ``4096``).
51+ 
38-   Unlike :class:`asyncore.dispatcher`, :class:`async_chat` allows you to define a
52+   Unlike :class:`asyncore.dispatcher`, :class:`async_chat` allows you to
39-   first-in-first-out queue (fifo) of *producers*. A producer need have only one
53+   define a first-in-first-out queue (fifo) of *producers*. A producer need
40-   method, :meth:`more`, which should return data to be transmitted on the channel.
54+   have only one method, :meth:`more`, which should return data to be
55+   transmitted on the channel.
41   The producer indicates exhaustion (*i.e.* that it contains no more data) by
42   having its :meth:`more` method return the empty string. At this point the
n43-   :class:`async_chat` object removes the producer from the fifo and starts using
n58+   :class:`async_chat` object removes the producer from the fifo and starts
44-   the next producer, if any. When the producer fifo is empty the
59+   using the next producer, if any. When the producer fifo is empty the
45   :meth:`handle_write` method does nothing. You use the channel object's
n46-   :meth:`set_terminator` method to describe how to recognize the end of, or an
n61+   :meth:`set_terminator` method to describe how to recognize the end of, or
47-   important breakpoint in, an incoming transmission from the remote endpoint.
62+   an important breakpoint in, an incoming transmission from the remote
63+   endpoint.
48
49   To build a functioning :class:`async_chat` subclass your  input methods
n50-   :meth:`collect_incoming_data` and :meth:`found_terminator` must handle the data
n66+   :meth:`collect_incoming_data` and :meth:`found_terminator` must handle the
51-   that the channel receives asynchronously. The methods are described below.
67+   data that the channel receives asynchronously. The methods are described
68+   below.
52
53
54.. method:: async_chat.close_when_done()
55
n56-   Pushes a ``None`` on to the producer fifo. When this producer is popped off the
n73+   Pushes a ``None`` on to the producer fifo. When this producer is popped off
57-   fifo it causes the channel to be closed.
74+   the fifo it causes the channel to be closed.
58
59
60.. method:: async_chat.collect_incoming_data(data)
61
n62-   Called with *data* holding an arbitrary amount of received data. The default
n79+   Called with *data* holding an arbitrary amount of received data.  The
63-   method, which must be overridden, raises a :exc:`NotImplementedError` exception.
80+   default method, which must be overridden, raises a
81+   :exc:`NotImplementedError` exception.
82+ 
83+ 
84+.. method:: async_chat._collect_incoming_data(data)
85+ 
86+   Sample implementation of a data collection rutine to be used in conjunction
87+   with :meth:`_get_data` in a user-specified :meth:`found_terminator`.
64
65
66.. method:: async_chat.discard_buffers()
67
n68-   In emergencies this method will discard any data held in the input and/or output
n92+   In emergencies this method will discard any data held in the input and/or
69-   buffers and the producer fifo.
93+   output buffers and the producer fifo.
70
71
72.. method:: async_chat.found_terminator()
73
n74-   Called when the incoming data stream  matches the termination condition set by
n98+   Called when the incoming data stream  matches the termination condition set
75-   :meth:`set_terminator`. The default method, which must be overridden, raises a
99+   by :meth:`set_terminator`. The default method, which must be overridden,
76-   :exc:`NotImplementedError` exception. The buffered input data should be
100+   raises a :exc:`NotImplementedError` exception. The buffered input data
77-   available via an instance attribute.
101+   should be available via an instance attribute.
102+ 
103+ 
104+.. method:: async_chat._get_data()
105+ 
106+   Will return and clear the data received with the sample
107+   :meth:`_collect_incoming_data` implementation.
78
79
80.. method:: async_chat.get_terminator()
81
82   Returns the current terminator for the channel.
83
84
85.. method:: async_chat.handle_close()
86
87   Called when the channel is closed. The default method silently closes the
88   channel's socket.
89
90
91.. method:: async_chat.handle_read()
92
n93-   Called when a read event fires on the channel's socket in the asynchronous loop.
n123+   Called when a read event fires on the channel's socket in the asynchronous
94-   The default method checks for the termination condition established by
124+   loop.  The default method checks for the termination condition established
95-   :meth:`set_terminator`, which can be either the appearance of a particular
125+   by :meth:`set_terminator`, which can be either the appearance of a
96-   string in the input stream or the receipt of a particular number of characters.
126+   particular string in the input stream or the receipt of a particular number
97-   When the terminator is found, :meth:`handle_read` calls the
127+   of characters.  When the terminator is found, :meth:`handle_read` calls the
98-   :meth:`found_terminator` method after calling :meth:`collect_incoming_data` with
128+   :meth:`found_terminator` method after calling :meth:`collect_incoming_data`
99-   any data preceding the terminating condition.
129+   with any data preceding the terminating condition.
100
101
102.. method:: async_chat.handle_write()
103
n104-   Called when the application may write data to the channel.   The default method
n134+   Called when the application may write data to the channel.   The default
105-   calls the :meth:`initiate_send` method, which in turn will call
135+   method calls the :meth:`initiate_send` method, which in turn will call
106-   :meth:`refill_buffer` to collect data from the producer fifo associated with the
136+   :meth:`refill_buffer` to collect data from the producer fifo associated
107-   channel.
137+   with the channel.
108
109
110.. method:: async_chat.push(data)
111
n112-   Creates a :class:`simple_producer` object (*see below*) containing the data and
n142+   Creates a :class:`simple_producer` object (*see below*) containing the data
113-   pushes it on to the channel's ``producer_fifo`` to ensure its transmission. This
143+   and pushes it on to the channel's ``producer_fifo`` to ensure its
114-   is all you need to do to have the channel write the data out to the network,
144+   transmission.  This is all you need to do to have the channel write the
115-   although it is possible to use your own producers in more complex schemes to
145+   data out to the network, although it is possible to use your own producers
116-   implement encryption and chunking, for example.
146+   in more complex schemes to implement encryption and chunking, for example.
117
118
119.. method:: async_chat.push_with_producer(producer)
120
n121-   Takes a producer object and adds it to the producer fifo associated with the
n151+   Takes a producer object and adds it to the producer fifo associated with
122-   channel. When all currently-pushed producers have been exhausted the channel
152+   the channel.  When all currently-pushed producers have been exhausted the
123-   will consume this producer's data by calling its :meth:`more` method and send
153+   channel will consume this producer's data by calling its :meth:`more`
124-   the data to the remote endpoint.
154+   method and send the data to the remote endpoint.
125
126
127.. method:: async_chat.readable()
128
n129-   Should return ``True`` for the channel to be included in the set of channels
n159+   Should return ``True`` for the channel to be included in the set of
130-   tested by the :cfunc:`select` loop for readability.
160+   channels tested by the :cfunc:`select` loop for readability.
131
132
133.. method:: async_chat.refill_buffer()
134
n135-   Refills the output buffer by calling the :meth:`more` method of the producer at
n165+   Refills the output buffer by calling the :meth:`more` method of the
136-   the head of the fifo. If it is exhausted then the producer is popped off the
166+   producer at the head of the fifo.  If it is exhausted then the producer is
137-   fifo and the next producer is activated. If the current producer is, or becomes,
167+   popped off the fifo and the next producer is activated.  If the current
138-   ``None`` then the channel is closed.
168+   producer is, or becomes, ``None`` then the channel is closed.
139
140
141.. method:: async_chat.set_terminator(term)
142
n143-   Sets the terminating condition to be recognised on the channel. ``term`` may be
n173+   Sets the terminating condition to be recognized on the channel.  ``term``
144-   any of three types of value, corresponding to three different ways to handle
174+   may be any of three types of value, corresponding to three different ways
145-   incoming protocol data.
175+   to handle incoming protocol data.
146
147   +-----------+---------------------------------------------+
148   | term      | Description                                 |
149   +===========+=============================================+
150   | *string*  | Will call :meth:`found_terminator` when the |
151   |           | string is found in the input stream         |
152   +-----------+---------------------------------------------+
153   | *integer* | Will call :meth:`found_terminator` when the |
154   |           | indicated number of characters have been    |
155   |           | received                                    |
156   +-----------+---------------------------------------------+
157   | ``None``  | The channel continues to collect data       |
158   |           | forever                                     |
159   +-----------+---------------------------------------------+
160
n161-   Note that any data following the terminator will be available for reading by the
n191+   Note that any data following the terminator will be available for reading
162-   channel after :meth:`found_terminator` is called.
192+   by the channel after :meth:`found_terminator` is called.
163
164
165.. method:: async_chat.writable()
166
167   Should return ``True`` as long as items remain on the producer fifo, or the
168   channel is connected and the channel's output buffer is non-empty.
169
170
171asynchat - Auxiliary Classes and Functions
172------------------------------------------
173
174
175.. class:: simple_producer(data[, buffer_size=512])
176
n177-   A :class:`simple_producer` takes a chunk of data and an optional buffer size.
n207+   A :class:`simple_producer` takes a chunk of data and an optional buffer
178-   Repeated calls to its :meth:`more` method yield successive chunks of the data no
208+   size.  Repeated calls to its :meth:`more` method yield successive chunks of
179-   larger than *buffer_size*.
209+   the data no larger than *buffer_size*.
180
181
n182-.. method:: simple_producer.more()
n212+   .. method:: more()
183
n184-   Produces the next chunk of information from the producer, or returns the empty
n214+      Produces the next chunk of information from the producer, or returns the
185-   string.
215+      empty string.
186
187
188.. class:: fifo([list=None])
189
n190-   Each channel maintains a :class:`fifo` holding data which has been pushed by the
n220+   Each channel maintains a :class:`fifo` holding data which has been pushed
191-   application but not yet popped for writing to the channel. A :class:`fifo` is a
221+   by the application but not yet popped for writing to the channel.  A
192-   list used to hold data and/or producers until they are required. If the *list*
222+   :class:`fifo` is a list used to hold data and/or producers until they are
193-   argument is provided then it should contain producers or data items to be
223+   required.  If the *list* argument is provided then it should contain
194-   written to the channel.
224+   producers or data items to be written to the channel.
195
196
n197-.. method:: fifo.is_empty()
n227+   .. method:: is_empty()
198
n199-   Returns ``True`` iff the fifo is empty.
n229+      Returns ``True`` if and only if the fifo is empty.
200
201
n202-.. method:: fifo.first()
n232+   .. method:: first()
203
n204-   Returns the least-recently :meth:`push`\ ed item from the fifo.
n234+      Returns the least-recently :meth:`push`\ ed item from the fifo.
205
206
n207-.. method:: fifo.push(data)
n237+   .. method:: push(data)
208
n209-   Adds the given data (which may be a string or a producer object) to the producer
n239+      Adds the given data (which may be a string or a producer object) to the
210-   fifo.
240+      producer fifo.
211
212
n213-.. method:: fifo.pop()
n243+   .. method:: pop()
214
n215-   If the fifo is not empty, returns ``True, first()``, deleting the popped item.
n245+      If the fifo is not empty, returns ``True, first()``, deleting the popped
216-   Returns ``False, None`` for an empty fifo.
246+      item.  Returns ``False, None`` for an empty fifo.
217
218The :mod:`asynchat` module also defines one utility function, which may be of
219use in network and textual analysis operations.
220
221
222.. function:: find_prefix_at_end(haystack, needle)
223
n224-   Returns ``True`` if string *haystack* ends with any non-empty prefix of string
n254+   Returns ``True`` if string *haystack* ends with any non-empty prefix of
225-   *needle*.
255+   string *needle*.
226
227
228.. _asynchat-example:
229
230asynchat Example
231----------------
232
233The following partial example shows how HTTP requests can be read with
n234-:class:`async_chat`. A web server might create an :class:`http_request_handler`
n264+:class:`async_chat`.  A web server might create an
235-object for each incoming client connection. Notice that initially the channel
265+:class:`http_request_handler` object for each incoming client connection.
236-terminator is set to match the blank line at the end of the HTTP headers, and a
266+Notice that initially the channel terminator is set to match the blank line at
237-flag indicates that the headers are being read.
267+the end of the HTTP headers, and a flag indicates that the headers are being
268+read.
238
n239-Once the headers have been read, if the request is of type POST (indicating that
n270+Once the headers have been read, if the request is of type POST (indicating
240-further data are present in the input stream) then the ``Content-Length:``
271+that further data are present in the input stream) then the
241-header is used to set a numeric terminator to read the right amount of data from
272+``Content-Length:`` header is used to set a numeric terminator to read the
242-the channel.
273+right amount of data from the channel.
243
244The :meth:`handle_request` method is called once all relevant input has been
n245-marshalled, after setting the channel terminator to ``None`` to ensure that any
n276+marshalled, after setting the channel terminator to ``None`` to ensure that
246-extraneous data sent by the web client are ignored. ::
277+any extraneous data sent by the web client are ignored. ::
247
248   class http_request_handler(asynchat.async_chat):
249
n250-       def __init__(self, conn, addr, sessions, log):
n281+       def __init__(self, sock, addr, sessions, log):
251-           asynchat.async_chat.__init__(self, conn=conn)
282+           asynchat.async_chat.__init__(self, sock=sock)
252           self.addr = addr
253           self.sessions = sessions
254           self.ibuffer = []
255           self.obuffer = ""
256           self.set_terminator("\r\n\r\n")
257           self.reading_headers = True
258           self.handling = False
259           self.cgi_data = None
276                   self.set_terminator(None)
277                   self.handle_request()
278           elif not self.handling:
279               self.set_terminator(None) # browsers sometimes over-send
280               self.cgi_data = parse(self.headers, "".join(self.ibuffer))
281               self.handling = True
282               self.ibuffer = []
283               self.handle_request()
t284- 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op