blob: 3b8eb1240f3b341516078c648d5a5b1ca4e94f9e [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`asynchat` --- Asynchronous socket command/response handler
2================================================================
3
4.. module:: asynchat
5 :synopsis: Support for asynchronous command/response protocols.
6.. moduleauthor:: Sam Rushing <rushing@nightmare.com>
Josiah Carlson35bf9bf2008-07-07 04:24:24 +00007.. sectionauthor:: Steve Holden <sholden@holdenweb.com>
Georg Brandl116aa622007-08-15 14:28:22 +00008
9
10This module builds on the :mod:`asyncore` infrastructure, simplifying
Georg Brandl9afde1c2007-11-01 20:32:30 +000011asynchronous clients and servers and making it easier to handle protocols
12whose elements are terminated by arbitrary strings, or are of variable length.
Georg Brandl116aa622007-08-15 14:28:22 +000013:mod:`asynchat` defines the abstract class :class:`async_chat` that you
14subclass, providing implementations of the :meth:`collect_incoming_data` and
15:meth:`found_terminator` methods. It uses the same asynchronous loop as
Georg Brandl9afde1c2007-11-01 20:32:30 +000016:mod:`asyncore`, and the two types of channel, :class:`asyncore.dispatcher`
17and :class:`asynchat.async_chat`, can freely be mixed in the channel map.
18Typically an :class:`asyncore.dispatcher` server channel generates new
19:class:`asynchat.async_chat` channel objects as it receives incoming
20connection requests.
Georg Brandl116aa622007-08-15 14:28:22 +000021
22
23.. class:: async_chat()
24
25 This class is an abstract subclass of :class:`asyncore.dispatcher`. To make
26 practical use of the code you must subclass :class:`async_chat`, providing
Georg Brandl9afde1c2007-11-01 20:32:30 +000027 meaningful :meth:`collect_incoming_data` and :meth:`found_terminator`
28 methods.
Georg Brandl116aa622007-08-15 14:28:22 +000029 The :class:`asyncore.dispatcher` methods can be used, although not all make
30 sense in a message/response context.
31
Georg Brandl9afde1c2007-11-01 20:32:30 +000032 Like :class:`asyncore.dispatcher`, :class:`async_chat` defines a set of
33 events that are generated by an analysis of socket conditions after a
34 :cfunc:`select` call. Once the polling loop has been started the
35 :class:`async_chat` object's methods are called by the event-processing
36 framework with no action on the part of the programmer.
Georg Brandl116aa622007-08-15 14:28:22 +000037
Georg Brandl9afde1c2007-11-01 20:32:30 +000038 Two class attributes can be modified, to improve performance, or possibly
39 even to conserve memory.
40
41
42 .. data:: ac_in_buffer_size
43
44 The asynchronous input buffer size (default ``4096``).
45
46
47 .. data:: ac_out_buffer_size
48
49 The asynchronous output buffer size (default ``4096``).
50
51 Unlike :class:`asyncore.dispatcher`, :class:`async_chat` allows you to
52 define a first-in-first-out queue (fifo) of *producers*. A producer need
53 have only one method, :meth:`more`, which should return data to be
54 transmitted on the channel.
Georg Brandl116aa622007-08-15 14:28:22 +000055 The producer indicates exhaustion (*i.e.* that it contains no more data) by
56 having its :meth:`more` method return the empty string. At this point the
Georg Brandl9afde1c2007-11-01 20:32:30 +000057 :class:`async_chat` object removes the producer from the fifo and starts
58 using the next producer, if any. When the producer fifo is empty the
Georg Brandl116aa622007-08-15 14:28:22 +000059 :meth:`handle_write` method does nothing. You use the channel object's
Georg Brandl9afde1c2007-11-01 20:32:30 +000060 :meth:`set_terminator` method to describe how to recognize the end of, or
61 an important breakpoint in, an incoming transmission from the remote
62 endpoint.
Georg Brandl116aa622007-08-15 14:28:22 +000063
64 To build a functioning :class:`async_chat` subclass your input methods
Georg Brandl9afde1c2007-11-01 20:32:30 +000065 :meth:`collect_incoming_data` and :meth:`found_terminator` must handle the
66 data that the channel receives asynchronously. The methods are described
67 below.
Georg Brandl116aa622007-08-15 14:28:22 +000068
69
70.. method:: async_chat.close_when_done()
71
Georg Brandl9afde1c2007-11-01 20:32:30 +000072 Pushes a ``None`` on to the producer fifo. When this producer is popped off
73 the fifo it causes the channel to be closed.
Georg Brandl116aa622007-08-15 14:28:22 +000074
75
76.. method:: async_chat.collect_incoming_data(data)
77
Georg Brandl9afde1c2007-11-01 20:32:30 +000078 Called with *data* holding an arbitrary amount of received data. The
79 default method, which must be overridden, raises a
80 :exc:`NotImplementedError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +000081
82
83.. method:: async_chat.discard_buffers()
84
Georg Brandl9afde1c2007-11-01 20:32:30 +000085 In emergencies this method will discard any data held in the input and/or
86 output buffers and the producer fifo.
Georg Brandl116aa622007-08-15 14:28:22 +000087
88
89.. method:: async_chat.found_terminator()
90
Georg Brandl9afde1c2007-11-01 20:32:30 +000091 Called when the incoming data stream matches the termination condition set
92 by :meth:`set_terminator`. The default method, which must be overridden,
93 raises a :exc:`NotImplementedError` exception. The buffered input data
94 should be available via an instance attribute.
Georg Brandl116aa622007-08-15 14:28:22 +000095
96
97.. method:: async_chat.get_terminator()
98
99 Returns the current terminator for the channel.
100
101
Georg Brandl116aa622007-08-15 14:28:22 +0000102.. method:: async_chat.push(data)
103
Giampaolo Rodolà135751e2010-04-29 20:47:09 +0000104 Pushes data on to the channel's fifo to ensure its transmission.
105 This is all you need to do to have the channel write the data out to the
106 network, although it is possible to use your own producers in more complex
107 schemes to implement encryption and chunking, for example.
Georg Brandl116aa622007-08-15 14:28:22 +0000108
109
110.. method:: async_chat.push_with_producer(producer)
111
Georg Brandl9afde1c2007-11-01 20:32:30 +0000112 Takes a producer object and adds it to the producer fifo associated with
113 the channel. When all currently-pushed producers have been exhausted the
114 channel will consume this producer's data by calling its :meth:`more`
115 method and send the data to the remote endpoint.
Georg Brandl116aa622007-08-15 14:28:22 +0000116
117
Georg Brandl116aa622007-08-15 14:28:22 +0000118.. method:: async_chat.set_terminator(term)
119
Georg Brandl9afde1c2007-11-01 20:32:30 +0000120 Sets the terminating condition to be recognized on the channel. ``term``
121 may be any of three types of value, corresponding to three different ways
122 to handle incoming protocol data.
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124 +-----------+---------------------------------------------+
125 | term | Description |
126 +===========+=============================================+
127 | *string* | Will call :meth:`found_terminator` when the |
128 | | string is found in the input stream |
129 +-----------+---------------------------------------------+
130 | *integer* | Will call :meth:`found_terminator` when the |
131 | | indicated number of characters have been |
132 | | received |
133 +-----------+---------------------------------------------+
134 | ``None`` | The channel continues to collect data |
135 | | forever |
136 +-----------+---------------------------------------------+
137
Georg Brandl9afde1c2007-11-01 20:32:30 +0000138 Note that any data following the terminator will be available for reading
139 by the channel after :meth:`found_terminator` is called.
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141
Giampaolo Rodolà135751e2010-04-29 20:47:09 +0000142asynchat - Auxiliary Classes
Georg Brandl116aa622007-08-15 14:28:22 +0000143------------------------------------------
144
Georg Brandlb868a662009-04-02 02:56:10 +0000145.. class:: fifo(list=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000146
Giampaolo Rodolà135751e2010-04-29 20:47:09 +0000147 A :class:`fifo` holding data which has been pushed by the application but
148 not yet popped for writing to the channel. A :class:`fifo` is a list used
149 to hold data and/or producers until they are required. If the *list*
150 argument is provided then it should contain producers or data items to be
151 written to the channel.
Georg Brandl116aa622007-08-15 14:28:22 +0000152
153
Benjamin Petersone41251e2008-04-25 01:59:09 +0000154 .. method:: is_empty()
Georg Brandl116aa622007-08-15 14:28:22 +0000155
Benjamin Petersone41251e2008-04-25 01:59:09 +0000156 Returns ``True`` if and only if the fifo is empty.
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158
Benjamin Petersone41251e2008-04-25 01:59:09 +0000159 .. method:: first()
Georg Brandl116aa622007-08-15 14:28:22 +0000160
Benjamin Petersone41251e2008-04-25 01:59:09 +0000161 Returns the least-recently :meth:`push`\ ed item from the fifo.
Georg Brandl116aa622007-08-15 14:28:22 +0000162
163
Benjamin Petersone41251e2008-04-25 01:59:09 +0000164 .. method:: push(data)
Georg Brandl116aa622007-08-15 14:28:22 +0000165
Benjamin Petersone41251e2008-04-25 01:59:09 +0000166 Adds the given data (which may be a string or a producer object) to the
167 producer fifo.
Georg Brandl116aa622007-08-15 14:28:22 +0000168
169
Benjamin Petersone41251e2008-04-25 01:59:09 +0000170 .. method:: pop()
Georg Brandl116aa622007-08-15 14:28:22 +0000171
Benjamin Petersone41251e2008-04-25 01:59:09 +0000172 If the fifo is not empty, returns ``True, first()``, deleting the popped
173 item. Returns ``False, None`` for an empty fifo.
Georg Brandl116aa622007-08-15 14:28:22 +0000174
Georg Brandl116aa622007-08-15 14:28:22 +0000175
176.. _asynchat-example:
177
178asynchat Example
179----------------
180
181The following partial example shows how HTTP requests can be read with
Georg Brandl9afde1c2007-11-01 20:32:30 +0000182:class:`async_chat`. A web server might create an
183:class:`http_request_handler` object for each incoming client connection.
184Notice that initially the channel terminator is set to match the blank line at
185the end of the HTTP headers, and a flag indicates that the headers are being
186read.
Georg Brandl116aa622007-08-15 14:28:22 +0000187
Georg Brandl9afde1c2007-11-01 20:32:30 +0000188Once the headers have been read, if the request is of type POST (indicating
189that further data are present in the input stream) then the
190``Content-Length:`` header is used to set a numeric terminator to read the
191right amount of data from the channel.
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193The :meth:`handle_request` method is called once all relevant input has been
Georg Brandl9afde1c2007-11-01 20:32:30 +0000194marshalled, after setting the channel terminator to ``None`` to ensure that
195any extraneous data sent by the web client are ignored. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000196
197 class http_request_handler(asynchat.async_chat):
198
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000199 def __init__(self, sock, addr, sessions, log):
200 asynchat.async_chat.__init__(self, sock=sock)
Georg Brandl116aa622007-08-15 14:28:22 +0000201 self.addr = addr
202 self.sessions = sessions
203 self.ibuffer = []
Josiah Carlson1893ce72008-07-07 04:23:14 +0000204 self.obuffer = b""
205 self.set_terminator(b"\r\n\r\n")
Georg Brandl116aa622007-08-15 14:28:22 +0000206 self.reading_headers = True
207 self.handling = False
208 self.cgi_data = None
209 self.log = log
210
211 def collect_incoming_data(self, data):
212 """Buffer the data"""
213 self.ibuffer.append(data)
214
215 def found_terminator(self):
216 if self.reading_headers:
217 self.reading_headers = False
218 self.parse_headers("".join(self.ibuffer))
219 self.ibuffer = []
Josiah Carlson1893ce72008-07-07 04:23:14 +0000220 if self.op.upper() == b"POST":
Georg Brandl116aa622007-08-15 14:28:22 +0000221 clen = self.headers.getheader("content-length")
222 self.set_terminator(int(clen))
223 else:
224 self.handling = True
225 self.set_terminator(None)
226 self.handle_request()
227 elif not self.handling:
228 self.set_terminator(None) # browsers sometimes over-send
Josiah Carlson1893ce72008-07-07 04:23:14 +0000229 self.cgi_data = parse(self.headers, b"".join(self.ibuffer))
Georg Brandl116aa622007-08-15 14:28:22 +0000230 self.handling = True
231 self.ibuffer = []
232 self.handle_request()