cpython: 8b71cd67f548 (original) (raw)
--- a/Doc/library/socketserver.rst
+++ b/Doc/library/socketserver.rst
@@ -10,16 +10,34 @@
The :mod:socketserver
module simplifies the task of writing network servers.
-There are four basic server classes: :class:TCPServer
uses the Internet TCP
-protocol, which provides for continuous streams of data between the client and
-server. :class:UDPServer
uses datagrams, which are discrete packets of
-information that may arrive out of order or be lost while in transit. The more
-infrequently used :class:UnixStreamServer
and :class:UnixDatagramServer
-classes are similar, but use Unix domain sockets; they're not available on
-non-Unix platforms. For more details on network programming, consult a book
-such as
-W. Richard Steven's UNIX Network Programming or Ralph Davis's Win32 Network
-Programming.
+There are four basic concrete server classes:
+
+
+.. class:: TCPServer(server_address, RequestHandlerClass, bind_and_activate=True)
+
- This uses the Internet TCP protocol, which provides for
- continuous streams of data between the client and server.
- If bind_and_activate is true, the constructor automatically attempts to
- invoke :meth:
~BaseServer.server_bind
and - :meth:
~BaseServer.server_activate
. The other parameters are passed to - the :class:
BaseServer
base class. +
+ +.. class:: UDPServer(server_address, RequestHandlerClass, bind_and_activate=True) +
- This uses datagrams, which are discrete packets of information that may
- arrive out of order or be lost while in transit. The parameters are
- the same as for :class:
TCPServer
. +
+ +.. class:: UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True)
UnixDatagramServer(server_address, RequestHandlerClass, bind_and_activate=True)[](#l1.38)
- These more infrequently used classes are similar to the TCP and
- UDP classes, but use Unix domain sockets; they're not available on
- non-Unix platforms. The parameters are the same as for
- :class:
TCPServer
. +
These four classes process requests :dfn:synchronously
; each request must be
completed before the next request can be started. This isn't suitable if each
@@ -31,10 +49,12 @@ support asynchronous behaviour.
Creating a server requires several steps. First, you must create a request
handler class by subclassing the :class:BaseRequestHandler
class and
-overriding its :meth:handle
method; this method will process incoming
+overriding its :meth:~BaseRequestHandler.handle
method;
+this method will process incoming
requests. Second, you must instantiate one of the server classes, passing it
the server's address and the request handler class. Then call the
-:meth:handle_request
or :meth:serve_forever
method of the server object to
+:meth:~BaseServer.handle_request
or
+:meth:~BaseServer.serve_forever
method of the server object to
process one or many requests. Finally, call :meth:~BaseServer.server_close
to close the socket.
@@ -76,18 +96,33 @@ Note that :class:UnixDatagramServer
de
stream server is the address family, which is simply repeated in both Unix
server classes.
-Forking and threading versions of each type of server can be created using the
-:class:ForkingMixIn
and :class:ThreadingMixIn
mix-in classes. For instance,
-a threading UDP server class is created as follows::
+
+.. class:: ForkingMixIn
ThreadingMixIn[](#l1.72)
- Forking and threading versions of each type of server can be created
- using these mix-in classes. For instance, :class:
ThreadingUDPServer
- is created as follows:: +
class ThreadingUDPServer(ThreadingMixIn, UDPServer):[](#l1.78)
pass[](#l1.79)
- The mix-in class comes first, since it overrides a method defined in
- :class:
UDPServer
. Setting the various attributes also changes the - behavior of the underlying server mechanism. +
-The mix-in class must come first, since it overrides a method defined in
-:class:UDPServer
. Setting the various attributes also change the
-behavior of the underlying server mechanism.
+.. class:: ForkingTCPServer
ForkingUDPServer[](#l1.91)
ThreadingTCPServer[](#l1.92)
ThreadingUDPServer[](#l1.93)
To implement a service, you must derive a class from :class:BaseRequestHandler
-and redefine its :meth:handle
method. You can then run various versions of
+and redefine its :meth:~BaseRequestHandler.handle
method.
+You can then run various versions of
the service by combining one of the server classes with your request handler
class. The request handler class must be different for datagram or stream
services. This can be hidden by using the handler subclasses
@@ -109,7 +144,7 @@ has requested. Here a threading or fork
In some cases, it may be appropriate to process part of a request synchronously,
but to finish processing in a forked child depending on the request data. This
can be implemented by using a synchronous server and doing an explicit fork in
-the request handler class :meth:handle
method.
+the request handler class :meth:~BaseRequestHandler.handle
method.
Another approach to handling multiple simultaneous requests in an environment
that supports neither threads nor :func:~os.fork
(or where these are too
@@ -127,227 +162,240 @@ connected for a long time (if threads or
Server Objects
--------------
-.. class:: BaseServer
+.. class:: BaseServer(server_address, RequestHandlerClass)
This is the superclass of all Server objects in the module. It defines the
interface, given below, but does not implement most of the methods, which is
- done in subclasses. The two parameters are stored in the respective
- :attr:
server_address
and :attr:RequestHandlerClass
attributes.
-.. method:: BaseServer.fileno()
- Return an integer file descriptor for the socket on which the server is
- listening. This function is most commonly passed to :mod:
selectors
, to - allow monitoring multiple servers in the same process.
Return an integer file descriptor for the socket on which the server is[](#l1.134)
listening. This function is most commonly passed to :mod:`selectors`, to[](#l1.135)
allow monitoring multiple servers in the same process.[](#l1.136)
-.. method:: BaseServer.handle_request()
- Process a single request. This function calls the following methods in
- order: :meth:
get_request
, :meth:verify_request
, and - :meth:
process_request
. If the user-provided :meth:handle
method of the - handler class raises an exception, the server's :meth:
handle_error
method - will be called. If no request is received within :attr:
self.timeout
- seconds, :meth:
handle_timeout
will be called and :meth:handle_request
- will return.
Process a single request. This function calls the following methods in[](#l1.149)
order: :meth:`get_request`, :meth:`verify_request`, and[](#l1.150)
:meth:`process_request`. If the user-provided[](#l1.151)
:meth:`~BaseRequestHandler.handle` method of the[](#l1.152)
handler class raises an exception, the server's :meth:`handle_error` method[](#l1.153)
will be called. If no request is received within :attr:`timeout`[](#l1.154)
seconds, :meth:`handle_timeout` will be called and :meth:`handle_request`[](#l1.155)
will return.[](#l1.156)
-.. method:: BaseServer.serve_forever(poll_interval=0.5)
- Handle requests until an explicit :meth:
shutdown
request. Poll for - shutdown every poll_interval seconds. Ignores :attr:
self.timeout
. It - also calls :meth:
service_actions
, which may be used by a subclass or mixin - to provide actions specific to a given service. For example, the
- :class:
ForkingMixIn
class uses :meth:service_actions
to clean up zombie - child processes.
Handle requests until an explicit :meth:`shutdown` request. Poll for[](#l1.168)
shutdown every *poll_interval* seconds.[](#l1.169)
Ignores the :attr:`timeout` attribute. It[](#l1.170)
also calls :meth:`service_actions`, which may be used by a subclass or mixin[](#l1.171)
to provide actions specific to a given service. For example, the[](#l1.172)
:class:`ForkingMixIn` class uses :meth:`service_actions` to clean up zombie[](#l1.173)
child processes.[](#l1.174)
.. versionchanged:: 3.3[](#l1.178)
Added ``service_actions`` call to the ``serve_forever`` method.[](#l1.179)
-.. method:: BaseServer.service_actions()
- This is called in the :meth:
serve_forever
loop. This method can be - overridden by subclasses or mixin classes to perform actions specific to
- a given service, such as cleanup actions.
This is called in the :meth:`serve_forever` loop. This method can be[](#l1.188)
overridden by subclasses or mixin classes to perform actions specific to[](#l1.189)
a given service, such as cleanup actions.[](#l1.190)
.. versionadded:: 3.3[](#l1.192)
- .. method:: shutdown() +
Tell the :meth:`serve_forever` loop to stop and wait until it does.[](#l1.197)
-.. method:: BaseServer.shutdown()
-.. method:: BaseServer.server_close()
The family of protocols to which the server's socket belongs.[](#l1.213)
Common examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`.[](#l1.214)
-.. attribute:: BaseServer.address_family
- The family of protocols to which the server's socket belongs.
- Common examples are :const:
socket.AF_INET
and :const:socket.AF_UNIX
.
The user-provided request handler class; an instance of this class is created[](#l1.222)
for each request.[](#l1.223)
-.. attribute:: BaseServer.RequestHandlerClass
The address on which the server is listening. The format of addresses varies[](#l1.231)
depending on the protocol family;[](#l1.232)
see the documentation for the :mod:`socket` module[](#l1.233)
for details. For Internet protocols, this is a tuple containing a string giving[](#l1.234)
the address, and an integer port number: ``('127.0.0.1', 80)``, for example.[](#l1.235)
-.. attribute:: BaseServer.server_address
- The address on which the server is listening. The format of addresses varies
- depending on the protocol family; see the documentation for the socket module
- for details. For Internet protocols, this is a tuple containing a string giving
- the address, and an integer port number:
('127.0.0.1', 80)
, for example.
The socket object on which the server will listen for incoming requests.[](#l1.245)
-.. attribute:: BaseServer.socket
- The server classes support the following class variables: +
- .. XXX should class variables be covered before instance variables, or vice versa?
- .. attribute:: allow_reuse_address +
Whether the server will allow the reuse of an address. This defaults to[](#l1.256)
:const:`False`, and can be set in subclasses to change the policy.[](#l1.257)
-The server classes support the following class variables: - -.. XXX should class variables be covered before instance variables, or vice versa?
-.. attribute:: BaseServer.allow_reuse_address -
- Whether the server will allow the reuse of an address. This defaults to
- :const:
False
, and can be set in subclasses to change the policy.
The size of the request queue. If it takes a long time to process a single[](#l1.269)
request, any requests that arrive while the server is busy are placed into a[](#l1.270)
queue, up to :attr:`request_queue_size` requests. Once the queue is full,[](#l1.271)
further requests from clients will get a "Connection denied" error. The default[](#l1.272)
value is usually 5, but this can be overridden by subclasses.[](#l1.273)
-.. attribute:: BaseServer.request_queue_size
- The size of the request queue. If it takes a long time to process a single
- request, any requests that arrive while the server is busy are placed into a
- queue, up to :attr:
request_queue_size
requests. Once the queue is full, - further requests from clients will get a "Connection denied" error. The default
- value is usually 5, but this can be overridden by subclasses.
The type of socket used by the server; :const:`socket.SOCK_STREAM` and[](#l1.284)
:const:`socket.SOCK_DGRAM` are two common values.[](#l1.285)
-.. attribute:: BaseServer.socket_type
- The type of socket used by the server; :const:
socket.SOCK_STREAM
and - :const:
socket.SOCK_DGRAM
are two common values.
Timeout duration, measured in seconds, or :const:`None` if no timeout is[](#l1.293)
desired. If :meth:`handle_request` receives no incoming requests within the[](#l1.294)
timeout period, the :meth:`handle_timeout` method is called.[](#l1.295)
-.. attribute:: BaseServer.timeout
- There are various server methods that can be overridden by subclasses of base
- server classes like :class:
TCPServer
; these methods aren't useful to external - users of the server object.
- Timeout duration, measured in seconds, or :const:
None
if no timeout is - desired. If :meth:
handle_request
receives no incoming requests within the - timeout period, the :meth:
handle_timeout
method is called.
- .. XXX should the default implementations of these be documented, or should
it be assumed that the user will look at socketserver.py?[](#l1.307)
- .. method:: finish_request() +
Actually processes the request by instantiating :attr:`RequestHandlerClass` and[](#l1.311)
calling its :meth:`~BaseRequestHandler.handle` method.[](#l1.312)
-There are various server methods that can be overridden by subclasses of base
-server classes like :class:TCPServer
; these methods aren't useful to external
-users of the server object.
-.. XXX should the default implementations of these be documented, or should
-.. method:: BaseServer.finish_request() -
- Actually processes the request by instantiating :attr:
RequestHandlerClass
and - calling its :meth:
handle
method.
Must accept a request from the socket, and return a 2-tuple containing the *new*[](#l1.327)
socket object to be used to communicate with the client, and the client's[](#l1.328)
address.[](#l1.329)
-.. method:: BaseServer.get_request()
- Must accept a request from the socket, and return a 2-tuple containing the new
- socket object to be used to communicate with the client, and the client's
- address.
This function is called if the :meth:`~BaseRequestHandler.handle`[](#l1.338)
method of a :attr:`RequestHandlerClass` instance raises[](#l1.339)
an exception. The default action is to print the traceback to[](#l1.340)
standard output and continue handling further requests.[](#l1.341)
-.. method:: BaseServer.handle_error(request, client_address)
- This function is called if the :attr:
RequestHandlerClass
's :meth:handle
- method raises an exception. The default action is to print the traceback to
- standard output and continue handling further requests.
This function is called when the :attr:`timeout` attribute has been set to a[](#l1.350)
value other than :const:`None` and the timeout period has passed with no[](#l1.351)
requests being received. The default action for forking servers is[](#l1.352)
to collect the status of any child processes that have exited, while[](#l1.353)
in threading servers this method does nothing.[](#l1.354)
-.. method:: BaseServer.handle_timeout()
- This function is called when the :attr:
timeout
attribute has been set to a - value other than :const:
None
and the timeout period has passed with no - requests being received. The default action for forking servers is
- to collect the status of any child processes that have exited, while
- in threading servers this method does nothing.
Calls :meth:`finish_request` to create an instance of the[](#l1.365)
:attr:`RequestHandlerClass`. If desired, this function can create a new process[](#l1.366)
or thread to handle the request; the :class:`ForkingMixIn` and[](#l1.367)
:class:`ThreadingMixIn` classes do this.[](#l1.368)
-.. method:: BaseServer.process_request(request, client_address)
- .. Is there any point in documenting the following two functions?
What would the purpose of overriding them be: initializing server[](#l1.373)
instance variables, adding new network families?[](#l1.374)
- Calls :meth:
finish_request
to create an instance of the - :attr:
RequestHandlerClass
. If desired, this function can create a new process - or thread to handle the request; the :class:
ForkingMixIn
and - :class:
ThreadingMixIn
classes do this.
- .. method:: server_activate() +
Called by the server's constructor to activate the server. The default behavior[](#l1.382)
for a TCP server just invokes :meth:`~socket.socket.listen`[](#l1.383)
on the server's socket. May be overridden.[](#l1.384)
-.. Is there any point in documenting the following two functions?
- What would the purpose of overriding them be: initializing server
- instance variables, adding new network families?
-.. method:: BaseServer.server_activate() -
- Called by the server's constructor to activate the server. The default behavior
- just :meth:
listen
\ s to the server's socket. May be overridden.
Called by the server's constructor to bind the socket to the desired address.[](#l1.396)
May be overridden.[](#l1.397)
-.. method:: BaseServer.server_bind()
Must return a Boolean value; if the value is :const:`True`, the request will[](#l1.405)
be processed, and if it's :const:`False`, the request will be denied. This[](#l1.406)
function can be overridden to implement access controls for a server. The[](#l1.407)
default implementation always returns :const:`True`.[](#l1.408)
-.. method:: BaseServer.verify_request(request, client_address) +Request Handler Objects +----------------------- + +.. class:: BaseRequestHandler
- Must return a Boolean value; if the value is :const:
True
, the request will - be processed, and if it's :const:
False
, the request will be denied. This - function can be overridden to implement access controls for a server. The
- default implementation always returns :const:
True
.
- This is the superclass of all request handler objects. It defines
- the interface, given below. A concrete request handler subclass must
- define a new :meth:
handle
method, and can override any of - the other methods. A new instance of the subclass is created for each
- request.
-RequestHandler Objects
-----------------------
-
-The request handler class must define a new :meth:handle
method, and can
-override any of the following methods. A new instance is created for each
-request.
- -.. method:: RequestHandler.finish() -
- Called after the :meth:
handle
method to perform any clean-up actions - required. The default implementation does nothing. If :meth:
setup
- raises an exception, this function will not be called.
Called before the :meth:`handle` method to perform any initialization actions[](#l1.442)
required. The default implementation does nothing.[](#l1.443)
-.. method:: RequestHandler.handle() -
- This function must do all the work required to service a request. The
- default implementation does nothing. Several instance attributes are
- available to it; the request is available as :attr:
self.request
; the client - address as :attr:
self.client_address
; and the server instance as - :attr:
self.server
, in case it needs access to per-server information.
- The type of :attr:
self.request
is different for datagram or stream - services. For stream services, :attr:
self.request
is a socket object; for - datagram services, :attr:
self.request
is a pair of string and socket. - However, this can be hidden by using the request handler subclasses
- :class:
StreamRequestHandler
or :class:DatagramRequestHandler
, which - override the :meth:
setup
and :meth:finish
methods, and provide - :attr:
self.rfile
and :attr:self.wfile
attributes. :attr:self.rfile
and - :attr:
self.wfile
can be read or written, respectively, to get the request - data or return data to the client.
This function must do all the work required to service a request. The[](#l1.464)
default implementation does nothing. Several instance attributes are[](#l1.465)
available to it; the request is available as :attr:`self.request`; the client[](#l1.466)
address as :attr:`self.client_address`; and the server instance as[](#l1.467)
:attr:`self.server`, in case it needs access to per-server information.[](#l1.468)
The type of :attr:`self.request` is different for datagram or stream[](#l1.470)
services. For stream services, :attr:`self.request` is a socket object; for[](#l1.471)
datagram services, :attr:`self.request` is a pair of string and socket.[](#l1.472)
-.. method:: RequestHandler.setup()
- .. method:: finish() +
Called after the :meth:`handle` method to perform any clean-up actions[](#l1.478)
required. The default implementation does nothing. If :meth:`setup`[](#l1.479)
raises an exception, this function will not be called.[](#l1.480)
- Called before the :meth:
handle
method to perform any initialization actions - required. The default implementation does nothing. +.. class:: StreamRequestHandler
DatagramRequestHandler[](#l1.486)
- These :class:
BaseRequestHandler
subclasses override the - :meth:
~BaseRequestHandler.setup
and :meth:~BaseRequestHandler.finish
- methods, and provide :attr:
self.rfile
and :attr:self.wfile
attributes. - The :attr:
self.rfile
and :attr:self.wfile
attributes can be - read or written, respectively, to get the request data or return data
- to the client.
Examples @@ -362,7 +410,7 @@ This is the server side:: class MyTCPHandler(socketserver.BaseRequestHandler): """
The RequestHandler class for our server.[](#l1.501)
The request handler class for our server.[](#l1.502)
It is instantiated once per connection to the server, and must override the handle() method to implement communication to the