blob: 7c8c8d52e03d95461b425ba5e80af3cb73d78a4a [file] [log] [blame]
Alexandre Vassalottice261952008-05-12 02:31:37 +00001:mod:`socketserver` --- A framework for network servers
Georg Brandl116aa622007-08-15 14:28:22 +00002=======================================================
3
Alexandre Vassalottice261952008-05-12 02:31:37 +00004.. module:: socketserver
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: A framework for network servers.
6
Raymond Hettinger469271d2011-01-27 20:38:46 +00007**Source code:** :source:`Lib/socketserver.py`
8
9--------------
10
Alexandre Vassalottice261952008-05-12 02:31:37 +000011The :mod:`socketserver` module simplifies the task of writing network servers.
Georg Brandl116aa622007-08-15 14:28:22 +000012
Martin Pantereac17b82016-02-19 03:27:46 +000013There are four basic concrete server classes:
14
15
16.. class:: TCPServer(server_address, RequestHandlerClass, bind_and_activate=True)
17
18 This uses the Internet TCP protocol, which provides for
19 continuous streams of data between the client and server.
20 If *bind_and_activate* is true, the constructor automatically attempts to
21 invoke :meth:`~BaseServer.server_bind` and
22 :meth:`~BaseServer.server_activate`. The other parameters are passed to
23 the :class:`BaseServer` base class.
24
25
26.. class:: UDPServer(server_address, RequestHandlerClass, bind_and_activate=True)
27
28 This uses datagrams, which are discrete packets of information that may
29 arrive out of order or be lost while in transit. The parameters are
30 the same as for :class:`TCPServer`.
31
32
33.. class:: UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True)
34 UnixDatagramServer(server_address, RequestHandlerClass, bind_and_activate=True)
35
36 These more infrequently used classes are similar to the TCP and
37 UDP classes, but use Unix domain sockets; they're not available on
38 non-Unix platforms. The parameters are the same as for
39 :class:`TCPServer`.
40
Georg Brandl116aa622007-08-15 14:28:22 +000041
42These four classes process requests :dfn:`synchronously`; each request must be
43completed before the next request can be started. This isn't suitable if each
44request takes a long time to complete, because it requires a lot of computation,
45or because it returns a lot of data which the client is slow to process. The
46solution is to create a separate process or thread to handle each request; the
47:class:`ForkingMixIn` and :class:`ThreadingMixIn` mix-in classes can be used to
48support asynchronous behaviour.
49
50Creating a server requires several steps. First, you must create a request
51handler class by subclassing the :class:`BaseRequestHandler` class and
Martin Pantereac17b82016-02-19 03:27:46 +000052overriding its :meth:`~BaseRequestHandler.handle` method;
53this method will process incoming
Georg Brandl116aa622007-08-15 14:28:22 +000054requests. Second, you must instantiate one of the server classes, passing it
Martin Panter0cab9c12016-04-13 00:36:52 +000055the server's address and the request handler class. It is recommended to use
56the server in a :keyword:`with` statement. Then call the
Martin Pantereac17b82016-02-19 03:27:46 +000057:meth:`~BaseServer.handle_request` or
58:meth:`~BaseServer.serve_forever` method of the server object to
Robert Collins1ee92832015-07-29 12:52:40 +120059process one or many requests. Finally, call :meth:`~BaseServer.server_close`
Serhiy Storchaka2b57c432018-12-19 08:09:46 +020060to close the socket (unless you used a :keyword:`!with` statement).
Georg Brandl116aa622007-08-15 14:28:22 +000061
62When inheriting from :class:`ThreadingMixIn` for threaded connection behavior,
63you should explicitly declare how you want your threads to behave on an abrupt
Florent Xicluna599d76b2011-11-11 19:56:26 +010064shutdown. The :class:`ThreadingMixIn` class defines an attribute
Georg Brandl116aa622007-08-15 14:28:22 +000065*daemon_threads*, which indicates whether or not the server should wait for
Florent Xicluna599d76b2011-11-11 19:56:26 +010066thread termination. You should set the flag explicitly if you would like
67threads to behave autonomously; the default is :const:`False`, meaning that
68Python will not exit until all threads created by :class:`ThreadingMixIn` have
69exited.
Georg Brandl116aa622007-08-15 14:28:22 +000070
71Server classes have the same external methods and attributes, no matter what
Georg Brandlfceab5a2008-01-19 20:08:23 +000072network protocol they use.
Georg Brandl116aa622007-08-15 14:28:22 +000073
74
75Server Creation Notes
76---------------------
77
78There are five classes in an inheritance diagram, four of which represent
79synchronous servers of four types::
80
81 +------------+
82 | BaseServer |
83 +------------+
84 |
85 v
86 +-----------+ +------------------+
87 | TCPServer |------->| UnixStreamServer |
88 +-----------+ +------------------+
89 |
90 v
91 +-----------+ +--------------------+
92 | UDPServer |------->| UnixDatagramServer |
93 +-----------+ +--------------------+
94
95Note that :class:`UnixDatagramServer` derives from :class:`UDPServer`, not from
96:class:`UnixStreamServer` --- the only difference between an IP and a Unix
97stream server is the address family, which is simply repeated in both Unix
98server classes.
99
Georg Brandl116aa622007-08-15 14:28:22 +0000100
Martin Pantereac17b82016-02-19 03:27:46 +0000101.. class:: ForkingMixIn
102 ThreadingMixIn
Georg Brandl116aa622007-08-15 14:28:22 +0000103
Martin Pantereac17b82016-02-19 03:27:46 +0000104 Forking and threading versions of each type of server can be created
105 using these mix-in classes. For instance, :class:`ThreadingUDPServer`
106 is created as follows::
107
108 class ThreadingUDPServer(ThreadingMixIn, UDPServer):
109 pass
110
111 The mix-in class comes first, since it overrides a method defined in
112 :class:`UDPServer`. Setting the various attributes also changes the
113 behavior of the underlying server mechanism.
114
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)287e6872016-06-03 05:44:47 +0000115 :class:`ForkingMixIn` and the Forking classes mentioned below are
116 only available on POSIX platforms that support :func:`~os.fork`.
Martin Pantereac17b82016-02-19 03:27:46 +0000117
Victor Stinnerdb8189b2018-01-29 12:10:22 +0100118 :meth:`socketserver.ForkingMixIn.server_close` waits until all child
Victor Stinner453bd0b2018-05-24 03:14:44 +0200119 processes complete, except if
120 :attr:`socketserver.ForkingMixIn.block_on_close` attribute is false.
Victor Stinnerdb8189b2018-01-29 12:10:22 +0100121
122 :meth:`socketserver.ThreadingMixIn.server_close` waits until all non-daemon
Victor Stinner453bd0b2018-05-24 03:14:44 +0200123 threads complete, except if
124 :attr:`socketserver.ThreadingMixIn.block_on_close` attribute is false. Use
125 daemonic threads by setting
Victor Stinnerdb8189b2018-01-29 12:10:22 +0100126 :data:`ThreadingMixIn.daemon_threads` to ``True`` to not wait until threads
127 complete.
128
129 .. versionchanged:: 3.7
130
131 :meth:`socketserver.ForkingMixIn.server_close` and
132 :meth:`socketserver.ThreadingMixIn.server_close` now waits until all
133 child processes and non-daemonic threads complete.
Victor Stinner453bd0b2018-05-24 03:14:44 +0200134 Add a new :attr:`socketserver.ForkingMixIn.block_on_close` class
135 attribute to opt-in for the pre-3.7 behaviour.
Victor Stinnerdb8189b2018-01-29 12:10:22 +0100136
137
Martin Pantereac17b82016-02-19 03:27:46 +0000138.. class:: ForkingTCPServer
139 ForkingUDPServer
140 ThreadingTCPServer
141 ThreadingUDPServer
142
143 These classes are pre-defined using the mix-in classes.
144
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146To implement a service, you must derive a class from :class:`BaseRequestHandler`
Martin Pantereac17b82016-02-19 03:27:46 +0000147and redefine its :meth:`~BaseRequestHandler.handle` method.
148You can then run various versions of
Georg Brandl116aa622007-08-15 14:28:22 +0000149the service by combining one of the server classes with your request handler
150class. The request handler class must be different for datagram or stream
151services. This can be hidden by using the handler subclasses
152:class:`StreamRequestHandler` or :class:`DatagramRequestHandler`.
153
154Of course, you still have to use your head! For instance, it makes no sense to
155use a forking server if the service contains state in memory that can be
156modified by different requests, since the modifications in the child process
157would never reach the initial state kept in the parent process and passed to
158each child. In this case, you can use a threading server, but you will probably
159have to use locks to protect the integrity of the shared data.
160
161On the other hand, if you are building an HTTP server where all data is stored
162externally (for instance, in the file system), a synchronous class will
163essentially render the service "deaf" while one request is being handled --
164which may be for a very long time if a client is slow to receive all the data it
165has requested. Here a threading or forking server is appropriate.
166
167In some cases, it may be appropriate to process part of a request synchronously,
168but to finish processing in a forked child depending on the request data. This
169can be implemented by using a synchronous server and doing an explicit fork in
Martin Pantereac17b82016-02-19 03:27:46 +0000170the request handler class :meth:`~BaseRequestHandler.handle` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000171
172Another approach to handling multiple simultaneous requests in an environment
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300173that supports neither threads nor :func:`~os.fork` (or where these are too
174expensive or inappropriate for the service) is to maintain an explicit table of
Charles-François Natali1d29cc52014-03-24 22:25:39 +0000175partially finished requests and to use :mod:`selectors` to decide which
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300176request to work on next (or whether to handle a new incoming request). This is
177particularly important for stream services where each client can potentially be
178connected for a long time (if threads or subprocesses cannot be used). See
179:mod:`asyncore` for another way to manage this.
Georg Brandl116aa622007-08-15 14:28:22 +0000180
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000181.. XXX should data and methods be intermingled, or separate?
182 how should the distinction between class and instance variables be drawn?
Georg Brandl116aa622007-08-15 14:28:22 +0000183
184
185Server Objects
186--------------
187
Martin Pantereac17b82016-02-19 03:27:46 +0000188.. class:: BaseServer(server_address, RequestHandlerClass)
Georg Brandl116aa622007-08-15 14:28:22 +0000189
Benjamin Petersond23f8222009-04-05 19:13:16 +0000190 This is the superclass of all Server objects in the module. It defines the
191 interface, given below, but does not implement most of the methods, which is
Martin Pantereac17b82016-02-19 03:27:46 +0000192 done in subclasses. The two parameters are stored in the respective
193 :attr:`server_address` and :attr:`RequestHandlerClass` attributes.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000194
195
Martin Pantereac17b82016-02-19 03:27:46 +0000196 .. method:: fileno()
Georg Brandl116aa622007-08-15 14:28:22 +0000197
Martin Pantereac17b82016-02-19 03:27:46 +0000198 Return an integer file descriptor for the socket on which the server is
199 listening. This function is most commonly passed to :mod:`selectors`, to
200 allow monitoring multiple servers in the same process.
Georg Brandl116aa622007-08-15 14:28:22 +0000201
202
Martin Pantereac17b82016-02-19 03:27:46 +0000203 .. method:: handle_request()
Georg Brandl116aa622007-08-15 14:28:22 +0000204
Martin Pantereac17b82016-02-19 03:27:46 +0000205 Process a single request. This function calls the following methods in
206 order: :meth:`get_request`, :meth:`verify_request`, and
207 :meth:`process_request`. If the user-provided
208 :meth:`~BaseRequestHandler.handle` method of the
209 handler class raises an exception, the server's :meth:`handle_error` method
210 will be called. If no request is received within :attr:`timeout`
211 seconds, :meth:`handle_timeout` will be called and :meth:`handle_request`
212 will return.
Georg Brandl116aa622007-08-15 14:28:22 +0000213
214
Martin Pantereac17b82016-02-19 03:27:46 +0000215 .. method:: serve_forever(poll_interval=0.5)
Georg Brandl116aa622007-08-15 14:28:22 +0000216
Martin Pantereac17b82016-02-19 03:27:46 +0000217 Handle requests until an explicit :meth:`shutdown` request. Poll for
218 shutdown every *poll_interval* seconds.
219 Ignores the :attr:`timeout` attribute. It
220 also calls :meth:`service_actions`, which may be used by a subclass or mixin
221 to provide actions specific to a given service. For example, the
222 :class:`ForkingMixIn` class uses :meth:`service_actions` to clean up zombie
223 child processes.
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000224
Martin Pantereac17b82016-02-19 03:27:46 +0000225 .. versionchanged:: 3.3
226 Added ``service_actions`` call to the ``serve_forever`` method.
Senthil Kumaran5e826e82011-05-26 00:22:59 +0800227
228
Martin Pantereac17b82016-02-19 03:27:46 +0000229 .. method:: service_actions()
Senthil Kumaran5e826e82011-05-26 00:22:59 +0800230
Martin Pantereac17b82016-02-19 03:27:46 +0000231 This is called in the :meth:`serve_forever` loop. This method can be
232 overridden by subclasses or mixin classes to perform actions specific to
233 a given service, such as cleanup actions.
Senthil Kumaran5e826e82011-05-26 00:22:59 +0800234
Martin Pantereac17b82016-02-19 03:27:46 +0000235 .. versionadded:: 3.3
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000236
Martin Pantereac17b82016-02-19 03:27:46 +0000237 .. method:: shutdown()
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000238
Martin Pantereac17b82016-02-19 03:27:46 +0000239 Tell the :meth:`serve_forever` loop to stop and wait until it does.
Georg Brandl116aa622007-08-15 14:28:22 +0000240
241
Martin Pantereac17b82016-02-19 03:27:46 +0000242 .. method:: server_close()
Robert Collins1ee92832015-07-29 12:52:40 +1200243
Martin Pantereac17b82016-02-19 03:27:46 +0000244 Clean up the server. May be overridden.
245
246
247 .. attribute:: address_family
248
249 The family of protocols to which the server's socket belongs.
250 Common examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`.
Robert Collins1ee92832015-07-29 12:52:40 +1200251
Robert Collins1ee92832015-07-29 12:52:40 +1200252
Martin Pantereac17b82016-02-19 03:27:46 +0000253 .. attribute:: RequestHandlerClass
Robert Collins1ee92832015-07-29 12:52:40 +1200254
Martin Pantereac17b82016-02-19 03:27:46 +0000255 The user-provided request handler class; an instance of this class is created
256 for each request.
Georg Brandl116aa622007-08-15 14:28:22 +0000257
Georg Brandl116aa622007-08-15 14:28:22 +0000258
Martin Pantereac17b82016-02-19 03:27:46 +0000259 .. attribute:: server_address
Georg Brandl116aa622007-08-15 14:28:22 +0000260
Martin Pantereac17b82016-02-19 03:27:46 +0000261 The address on which the server is listening. The format of addresses varies
262 depending on the protocol family;
263 see the documentation for the :mod:`socket` module
264 for details. For Internet protocols, this is a tuple containing a string giving
265 the address, and an integer port number: ``('127.0.0.1', 80)``, for example.
Georg Brandl116aa622007-08-15 14:28:22 +0000266
Georg Brandl116aa622007-08-15 14:28:22 +0000267
Martin Pantereac17b82016-02-19 03:27:46 +0000268 .. attribute:: socket
Georg Brandl116aa622007-08-15 14:28:22 +0000269
Martin Pantereac17b82016-02-19 03:27:46 +0000270 The socket object on which the server will listen for incoming requests.
Georg Brandl116aa622007-08-15 14:28:22 +0000271
Georg Brandl116aa622007-08-15 14:28:22 +0000272
Martin Pantereac17b82016-02-19 03:27:46 +0000273 The server classes support the following class variables:
Georg Brandl116aa622007-08-15 14:28:22 +0000274
Martin Pantereac17b82016-02-19 03:27:46 +0000275 .. XXX should class variables be covered before instance variables, or vice versa?
Georg Brandl116aa622007-08-15 14:28:22 +0000276
Martin Pantereac17b82016-02-19 03:27:46 +0000277 .. attribute:: allow_reuse_address
Georg Brandl116aa622007-08-15 14:28:22 +0000278
Martin Pantereac17b82016-02-19 03:27:46 +0000279 Whether the server will allow the reuse of an address. This defaults to
280 :const:`False`, and can be set in subclasses to change the policy.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000281
Georg Brandl116aa622007-08-15 14:28:22 +0000282
Martin Pantereac17b82016-02-19 03:27:46 +0000283 .. attribute:: request_queue_size
Georg Brandl116aa622007-08-15 14:28:22 +0000284
Martin Pantereac17b82016-02-19 03:27:46 +0000285 The size of the request queue. If it takes a long time to process a single
286 request, any requests that arrive while the server is busy are placed into a
287 queue, up to :attr:`request_queue_size` requests. Once the queue is full,
288 further requests from clients will get a "Connection denied" error. The default
289 value is usually 5, but this can be overridden by subclasses.
Georg Brandl116aa622007-08-15 14:28:22 +0000290
Georg Brandl116aa622007-08-15 14:28:22 +0000291
Martin Pantereac17b82016-02-19 03:27:46 +0000292 .. attribute:: socket_type
Georg Brandl116aa622007-08-15 14:28:22 +0000293
Martin Pantereac17b82016-02-19 03:27:46 +0000294 The type of socket used by the server; :const:`socket.SOCK_STREAM` and
295 :const:`socket.SOCK_DGRAM` are two common values.
Georg Brandl116aa622007-08-15 14:28:22 +0000296
Georg Brandl116aa622007-08-15 14:28:22 +0000297
Martin Pantereac17b82016-02-19 03:27:46 +0000298 .. attribute:: timeout
Georg Brandl116aa622007-08-15 14:28:22 +0000299
Martin Pantereac17b82016-02-19 03:27:46 +0000300 Timeout duration, measured in seconds, or :const:`None` if no timeout is
301 desired. If :meth:`handle_request` receives no incoming requests within the
302 timeout period, the :meth:`handle_timeout` method is called.
Georg Brandl116aa622007-08-15 14:28:22 +0000303
Georg Brandl116aa622007-08-15 14:28:22 +0000304
Martin Pantereac17b82016-02-19 03:27:46 +0000305 There are various server methods that can be overridden by subclasses of base
306 server classes like :class:`TCPServer`; these methods aren't useful to external
307 users of the server object.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000308
Martin Pantereac17b82016-02-19 03:27:46 +0000309 .. XXX should the default implementations of these be documented, or should
310 it be assumed that the user will look at socketserver.py?
Georg Brandlfceab5a2008-01-19 20:08:23 +0000311
Masayuki Yamamoto7750bde2017-11-19 16:33:37 +0900312 .. method:: finish_request(request, client_address)
Georg Brandlfceab5a2008-01-19 20:08:23 +0000313
Martin Pantereac17b82016-02-19 03:27:46 +0000314 Actually processes the request by instantiating :attr:`RequestHandlerClass` and
315 calling its :meth:`~BaseRequestHandler.handle` method.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000316
Georg Brandl116aa622007-08-15 14:28:22 +0000317
Martin Pantereac17b82016-02-19 03:27:46 +0000318 .. method:: get_request()
Georg Brandl116aa622007-08-15 14:28:22 +0000319
Martin Pantereac17b82016-02-19 03:27:46 +0000320 Must accept a request from the socket, and return a 2-tuple containing the *new*
321 socket object to be used to communicate with the client, and the client's
322 address.
Georg Brandl116aa622007-08-15 14:28:22 +0000323
Georg Brandl116aa622007-08-15 14:28:22 +0000324
Martin Pantereac17b82016-02-19 03:27:46 +0000325 .. method:: handle_error(request, client_address)
Georg Brandl116aa622007-08-15 14:28:22 +0000326
Martin Pantereac17b82016-02-19 03:27:46 +0000327 This function is called if the :meth:`~BaseRequestHandler.handle`
328 method of a :attr:`RequestHandlerClass` instance raises
329 an exception. The default action is to print the traceback to
Martin Panterd9108d12016-02-21 08:49:56 +0000330 standard error and continue handling further requests.
331
332 .. versionchanged:: 3.6
333 Now only called for exceptions derived from the :exc:`Exception`
334 class.
Georg Brandl116aa622007-08-15 14:28:22 +0000335
Georg Brandl116aa622007-08-15 14:28:22 +0000336
Martin Pantereac17b82016-02-19 03:27:46 +0000337 .. method:: handle_timeout()
Georg Brandl116aa622007-08-15 14:28:22 +0000338
Martin Pantereac17b82016-02-19 03:27:46 +0000339 This function is called when the :attr:`timeout` attribute has been set to a
340 value other than :const:`None` and the timeout period has passed with no
341 requests being received. The default action for forking servers is
342 to collect the status of any child processes that have exited, while
343 in threading servers this method does nothing.
Georg Brandl116aa622007-08-15 14:28:22 +0000344
Georg Brandl116aa622007-08-15 14:28:22 +0000345
Martin Pantereac17b82016-02-19 03:27:46 +0000346 .. method:: process_request(request, client_address)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000347
Martin Pantereac17b82016-02-19 03:27:46 +0000348 Calls :meth:`finish_request` to create an instance of the
349 :attr:`RequestHandlerClass`. If desired, this function can create a new process
350 or thread to handle the request; the :class:`ForkingMixIn` and
351 :class:`ThreadingMixIn` classes do this.
Georg Brandlfceab5a2008-01-19 20:08:23 +0000352
Georg Brandl116aa622007-08-15 14:28:22 +0000353
Martin Pantereac17b82016-02-19 03:27:46 +0000354 .. Is there any point in documenting the following two functions?
355 What would the purpose of overriding them be: initializing server
356 instance variables, adding new network families?
Benjamin Petersond23f8222009-04-05 19:13:16 +0000357
Martin Pantereac17b82016-02-19 03:27:46 +0000358 .. method:: server_activate()
Georg Brandl116aa622007-08-15 14:28:22 +0000359
Martin Pantereac17b82016-02-19 03:27:46 +0000360 Called by the server's constructor to activate the server. The default behavior
361 for a TCP server just invokes :meth:`~socket.socket.listen`
362 on the server's socket. May be overridden.
Georg Brandl116aa622007-08-15 14:28:22 +0000363
Benjamin Petersond23f8222009-04-05 19:13:16 +0000364
Martin Pantereac17b82016-02-19 03:27:46 +0000365 .. method:: server_bind()
Georg Brandl116aa622007-08-15 14:28:22 +0000366
Martin Pantereac17b82016-02-19 03:27:46 +0000367 Called by the server's constructor to bind the socket to the desired address.
368 May be overridden.
Georg Brandl116aa622007-08-15 14:28:22 +0000369
Georg Brandl116aa622007-08-15 14:28:22 +0000370
Martin Pantereac17b82016-02-19 03:27:46 +0000371 .. method:: verify_request(request, client_address)
Georg Brandl116aa622007-08-15 14:28:22 +0000372
Martin Pantereac17b82016-02-19 03:27:46 +0000373 Must return a Boolean value; if the value is :const:`True`, the request will
374 be processed, and if it's :const:`False`, the request will be denied. This
375 function can be overridden to implement access controls for a server. The
376 default implementation always returns :const:`True`.
Georg Brandl116aa622007-08-15 14:28:22 +0000377
Georg Brandl116aa622007-08-15 14:28:22 +0000378
Martin Panter0cab9c12016-04-13 00:36:52 +0000379 .. versionchanged:: 3.6
380 Support for the :term:`context manager` protocol was added. Exiting the
381 context manager is equivalent to calling :meth:`server_close`.
382
383
Martin Pantereac17b82016-02-19 03:27:46 +0000384Request Handler Objects
385-----------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000386
Martin Pantereac17b82016-02-19 03:27:46 +0000387.. class:: BaseRequestHandler
Georg Brandl116aa622007-08-15 14:28:22 +0000388
Martin Pantereac17b82016-02-19 03:27:46 +0000389 This is the superclass of all request handler objects. It defines
390 the interface, given below. A concrete request handler subclass must
391 define a new :meth:`handle` method, and can override any of
392 the other methods. A new instance of the subclass is created for each
393 request.
Georg Brandl116aa622007-08-15 14:28:22 +0000394
395
Martin Pantereac17b82016-02-19 03:27:46 +0000396 .. method:: setup()
Georg Brandl116aa622007-08-15 14:28:22 +0000397
Martin Pantereac17b82016-02-19 03:27:46 +0000398 Called before the :meth:`handle` method to perform any initialization actions
399 required. The default implementation does nothing.
Georg Brandl116aa622007-08-15 14:28:22 +0000400
401
Martin Pantereac17b82016-02-19 03:27:46 +0000402 .. method:: handle()
Georg Brandl116aa622007-08-15 14:28:22 +0000403
Martin Pantereac17b82016-02-19 03:27:46 +0000404 This function must do all the work required to service a request. The
405 default implementation does nothing. Several instance attributes are
406 available to it; the request is available as :attr:`self.request`; the client
407 address as :attr:`self.client_address`; and the server instance as
408 :attr:`self.server`, in case it needs access to per-server information.
Georg Brandl116aa622007-08-15 14:28:22 +0000409
Martin Pantereac17b82016-02-19 03:27:46 +0000410 The type of :attr:`self.request` is different for datagram or stream
411 services. For stream services, :attr:`self.request` is a socket object; for
412 datagram services, :attr:`self.request` is a pair of string and socket.
Georg Brandl116aa622007-08-15 14:28:22 +0000413
Georg Brandl116aa622007-08-15 14:28:22 +0000414
Martin Pantereac17b82016-02-19 03:27:46 +0000415 .. method:: finish()
Georg Brandl116aa622007-08-15 14:28:22 +0000416
Martin Pantereac17b82016-02-19 03:27:46 +0000417 Called after the :meth:`handle` method to perform any clean-up actions
418 required. The default implementation does nothing. If :meth:`setup`
419 raises an exception, this function will not be called.
Georg Brandl116aa622007-08-15 14:28:22 +0000420
421
Martin Pantereac17b82016-02-19 03:27:46 +0000422.. class:: StreamRequestHandler
423 DatagramRequestHandler
Georg Brandl116aa622007-08-15 14:28:22 +0000424
Martin Pantereac17b82016-02-19 03:27:46 +0000425 These :class:`BaseRequestHandler` subclasses override the
426 :meth:`~BaseRequestHandler.setup` and :meth:`~BaseRequestHandler.finish`
427 methods, and provide :attr:`self.rfile` and :attr:`self.wfile` attributes.
428 The :attr:`self.rfile` and :attr:`self.wfile` attributes can be
429 read or written, respectively, to get the request data or return data
430 to the client.
Georg Brandl116aa622007-08-15 14:28:22 +0000431
Martin Panter34eeed42016-06-29 10:12:22 +0000432 The :attr:`rfile` attributes of both classes support the
433 :class:`io.BufferedIOBase` readable interface, and
434 :attr:`DatagramRequestHandler.wfile` supports the
435 :class:`io.BufferedIOBase` writable interface.
436
437 .. versionchanged:: 3.6
438 :attr:`StreamRequestHandler.wfile` also supports the
439 :class:`io.BufferedIOBase` writable interface.
440
Georg Brandlb533e262008-05-25 18:19:30 +0000441
442Examples
443--------
444
445:class:`socketserver.TCPServer` Example
446~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
447
448This is the server side::
449
450 import socketserver
451
452 class MyTCPHandler(socketserver.BaseRequestHandler):
453 """
Martin Pantereac17b82016-02-19 03:27:46 +0000454 The request handler class for our server.
Georg Brandlb533e262008-05-25 18:19:30 +0000455
456 It is instantiated once per connection to the server, and must
457 override the handle() method to implement communication to the
458 client.
459 """
460
461 def handle(self):
462 # self.request is the TCP socket connected to the client
463 self.data = self.request.recv(1024).strip()
Florent Xicluna023611f2011-10-23 22:40:37 +0200464 print("{} wrote:".format(self.client_address[0]))
Benjamin Peterson06fd5f82008-11-08 17:24:34 +0000465 print(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000466 # just send back the same data, but upper-cased
Senthil Kumaran6e13f132012-02-09 17:54:17 +0800467 self.request.sendall(self.data.upper())
Georg Brandlb533e262008-05-25 18:19:30 +0000468
469 if __name__ == "__main__":
470 HOST, PORT = "localhost", 9999
471
472 # Create the server, binding to localhost on port 9999
Martin Panter0cab9c12016-04-13 00:36:52 +0000473 with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
474 # Activate the server; this will keep running until you
475 # interrupt the program with Ctrl-C
476 server.serve_forever()
Georg Brandlb533e262008-05-25 18:19:30 +0000477
478An alternative request handler class that makes use of streams (file-like
479objects that simplify communication by providing the standard file interface)::
480
481 class MyTCPHandler(socketserver.StreamRequestHandler):
482
483 def handle(self):
484 # self.rfile is a file-like object created by the handler;
485 # we can now use e.g. readline() instead of raw recv() calls
486 self.data = self.rfile.readline().strip()
Florent Xicluna023611f2011-10-23 22:40:37 +0200487 print("{} wrote:".format(self.client_address[0]))
Benjamin Peterson06fd5f82008-11-08 17:24:34 +0000488 print(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000489 # Likewise, self.wfile is a file-like object used to write back
490 # to the client
491 self.wfile.write(self.data.upper())
492
493The difference is that the ``readline()`` call in the second handler will call
494``recv()`` multiple times until it encounters a newline character, while the
495single ``recv()`` call in the first handler will just return what has been sent
Senthil Kumaran6e13f132012-02-09 17:54:17 +0800496from the client in one ``sendall()`` call.
Georg Brandlb533e262008-05-25 18:19:30 +0000497
498
499This is the client side::
500
501 import socket
502 import sys
503
504 HOST, PORT = "localhost", 9999
505 data = " ".join(sys.argv[1:])
506
507 # Create a socket (SOCK_STREAM means a TCP socket)
Martin Pantere37fc182016-04-24 04:24:36 +0000508 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
Florent Xicluna023611f2011-10-23 22:40:37 +0200509 # Connect to server and send data
510 sock.connect((HOST, PORT))
Senthil Kumaran6e13f132012-02-09 17:54:17 +0800511 sock.sendall(bytes(data + "\n", "utf-8"))
Georg Brandlb533e262008-05-25 18:19:30 +0000512
Florent Xicluna023611f2011-10-23 22:40:37 +0200513 # Receive data from the server and shut down
514 received = str(sock.recv(1024), "utf-8")
Georg Brandlb533e262008-05-25 18:19:30 +0000515
Florent Xicluna023611f2011-10-23 22:40:37 +0200516 print("Sent: {}".format(data))
517 print("Received: {}".format(received))
Georg Brandlb533e262008-05-25 18:19:30 +0000518
519
520The output of the example should look something like this:
521
Martin Panter1050d2d2016-07-26 11:18:21 +0200522Server:
523
524.. code-block:: shell-session
Georg Brandlb533e262008-05-25 18:19:30 +0000525
526 $ python TCPServer.py
527 127.0.0.1 wrote:
Benjamin Peterson06fd5f82008-11-08 17:24:34 +0000528 b'hello world with TCP'
Georg Brandlb533e262008-05-25 18:19:30 +0000529 127.0.0.1 wrote:
Benjamin Peterson06fd5f82008-11-08 17:24:34 +0000530 b'python is nice'
Georg Brandlb533e262008-05-25 18:19:30 +0000531
Martin Panter1050d2d2016-07-26 11:18:21 +0200532Client:
533
534.. code-block:: shell-session
Georg Brandlb533e262008-05-25 18:19:30 +0000535
536 $ python TCPClient.py hello world with TCP
537 Sent: hello world with TCP
Florent Xicluna023611f2011-10-23 22:40:37 +0200538 Received: HELLO WORLD WITH TCP
Georg Brandlb533e262008-05-25 18:19:30 +0000539 $ python TCPClient.py python is nice
540 Sent: python is nice
Florent Xicluna023611f2011-10-23 22:40:37 +0200541 Received: PYTHON IS NICE
Georg Brandlb533e262008-05-25 18:19:30 +0000542
543
544:class:`socketserver.UDPServer` Example
545~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
546
547This is the server side::
548
549 import socketserver
550
551 class MyUDPHandler(socketserver.BaseRequestHandler):
552 """
553 This class works similar to the TCP handler class, except that
554 self.request consists of a pair of data and client socket, and since
555 there is no connection the client address must be given explicitly
556 when sending data back via sendto().
557 """
558
559 def handle(self):
560 data = self.request[0].strip()
561 socket = self.request[1]
Florent Xicluna023611f2011-10-23 22:40:37 +0200562 print("{} wrote:".format(self.client_address[0]))
Benjamin Peterson06fd5f82008-11-08 17:24:34 +0000563 print(data)
Georg Brandlb533e262008-05-25 18:19:30 +0000564 socket.sendto(data.upper(), self.client_address)
565
566 if __name__ == "__main__":
Benjamin Peterson20211002009-11-25 18:34:42 +0000567 HOST, PORT = "localhost", 9999
Martin Panter0cab9c12016-04-13 00:36:52 +0000568 with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server:
569 server.serve_forever()
Georg Brandlb533e262008-05-25 18:19:30 +0000570
571This is the client side::
572
573 import socket
574 import sys
575
Benjamin Peterson06fd5f82008-11-08 17:24:34 +0000576 HOST, PORT = "localhost", 9999
Georg Brandlb533e262008-05-25 18:19:30 +0000577 data = " ".join(sys.argv[1:])
578
579 # SOCK_DGRAM is the socket type to use for UDP sockets
580 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
581
582 # As you can see, there is no connect() call; UDP has no connections.
583 # Instead, data is directly sent to the recipient via sendto().
Florent Xicluna023611f2011-10-23 22:40:37 +0200584 sock.sendto(bytes(data + "\n", "utf-8"), (HOST, PORT))
585 received = str(sock.recv(1024), "utf-8")
Georg Brandlb533e262008-05-25 18:19:30 +0000586
Florent Xicluna023611f2011-10-23 22:40:37 +0200587 print("Sent: {}".format(data))
588 print("Received: {}".format(received))
Georg Brandlb533e262008-05-25 18:19:30 +0000589
590The output of the example should look exactly like for the TCP server example.
591
592
593Asynchronous Mixins
594~~~~~~~~~~~~~~~~~~~
595
596To build asynchronous handlers, use the :class:`ThreadingMixIn` and
597:class:`ForkingMixIn` classes.
598
599An example for the :class:`ThreadingMixIn` class::
600
601 import socket
602 import threading
603 import socketserver
604
605 class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
606
607 def handle(self):
Florent Xicluna023611f2011-10-23 22:40:37 +0200608 data = str(self.request.recv(1024), 'ascii')
Georg Brandlf9926402008-06-13 06:32:25 +0000609 cur_thread = threading.current_thread()
Florent Xicluna023611f2011-10-23 22:40:37 +0200610 response = bytes("{}: {}".format(cur_thread.name, data), 'ascii')
Senthil Kumaran6e13f132012-02-09 17:54:17 +0800611 self.request.sendall(response)
Georg Brandlb533e262008-05-25 18:19:30 +0000612
613 class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
614 pass
615
616 def client(ip, port, message):
Martin Pantere37fc182016-04-24 04:24:36 +0000617 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
618 sock.connect((ip, port))
Senthil Kumaran6e13f132012-02-09 17:54:17 +0800619 sock.sendall(bytes(message, 'ascii'))
Florent Xicluna023611f2011-10-23 22:40:37 +0200620 response = str(sock.recv(1024), 'ascii')
621 print("Received: {}".format(response))
Georg Brandlb533e262008-05-25 18:19:30 +0000622
623 if __name__ == "__main__":
624 # Port 0 means to select an arbitrary unused port
625 HOST, PORT = "localhost", 0
626
627 server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
Martin Panter0cab9c12016-04-13 00:36:52 +0000628 with server:
629 ip, port = server.server_address
Georg Brandlb533e262008-05-25 18:19:30 +0000630
Martin Panter0cab9c12016-04-13 00:36:52 +0000631 # Start a thread with the server -- that thread will then start one
632 # more thread for each request
633 server_thread = threading.Thread(target=server.serve_forever)
634 # Exit the server thread when the main thread terminates
635 server_thread.daemon = True
636 server_thread.start()
637 print("Server loop running in thread:", server_thread.name)
Georg Brandlb533e262008-05-25 18:19:30 +0000638
Martin Panter0cab9c12016-04-13 00:36:52 +0000639 client(ip, port, "Hello World 1")
640 client(ip, port, "Hello World 2")
641 client(ip, port, "Hello World 3")
Georg Brandlb533e262008-05-25 18:19:30 +0000642
Martin Panter0cab9c12016-04-13 00:36:52 +0000643 server.shutdown()
Georg Brandlb533e262008-05-25 18:19:30 +0000644
Benjamin Peterson06fd5f82008-11-08 17:24:34 +0000645
Martin Panter1050d2d2016-07-26 11:18:21 +0200646The output of the example should look something like this:
647
648.. code-block:: shell-session
Georg Brandlb533e262008-05-25 18:19:30 +0000649
650 $ python ThreadedTCPServer.py
651 Server loop running in thread: Thread-1
Florent Xicluna023611f2011-10-23 22:40:37 +0200652 Received: Thread-2: Hello World 1
653 Received: Thread-3: Hello World 2
654 Received: Thread-4: Hello World 3
Georg Brandlb533e262008-05-25 18:19:30 +0000655
656
657The :class:`ForkingMixIn` class is used in the same way, except that the server
658will spawn a new process for each request.
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)287e6872016-06-03 05:44:47 +0000659Available only on POSIX platforms that support :func:`~os.fork`.
660