Python Manual Benutzerhandbuch

Seite von 124
Servlet Framework
92
return netsvc.ErrorServlet(404)
daemon = netsvc.HttpDaemon(8000)
server = HttpServer()
daemon.attach("/test",server)
daemon.start()
The job of the "
servlet()
" member function is to create an instance of a HTTP servlet capable of
handling a request made against a specific URL. When the "
servlet()
" member function is called
it is supplied with the HTTP session object. The session object provides access to details of the request,
including the server root and servlet path. The server root corresponds to the path under which the
HTTP server object was registered. The servlet path is the remainder of the path expressed relative to
that server root.
As an example, if the request used the path "
/test/echo
" and the HTTP server object was regis-
tered with the path "
/test
", the server root would be "
/test
" and the servlet path would be "
echo
".
In the case that a HTTP server object is registered with path "
/
", the server root will still be "
/
". This
is the only case where the trailing "
/
" isn’t removed.
Under normal circumstances the HTTP server object would determine the type of HTTP servlet to cre-
ate and the resource being referenced based only on the servlet path. If necessary however, it can query
other information related to a request. Such a circumstance might be to look for the presence of cookies
used to implement a user session mechanism.
When a HTTP servlet is created, it will need to be passed the handle to the HTTP session object. All
the predefined HTTP servlets accept this as the first argument when the servlet is created. If you are
defining your own servlets, it is recommended you follow this convention.
If the HTTP server object isn’t able to map a request to a particular type of HTTP servlet, the "
serv-
let()
" member function should return "
None
", or should indicate a specific type of HTTP error re-
sponse using the
ErrorServlet
class. A HTTP client can be redirected to a different resource using
the
RedirectServlet
class.
The Error Servlet
The error servlet as implemented by the
ErrorServlet
class is provided as a quick way for a cus-
tom HTTP server object to return a HTTP error response. In addition to the the HTTP session object,
the error servlet needs to be supplied with an approriate HTTP error response code. Text to be included
in the body of the response can also be provided if desired. Such text may include any relevant HTML
markup, but should not include the opening and closing "
body
" tags.
class HttpServer(netsvc.HttpServer):
def servlet(self,session):
return netsvc.ErrorServlet(session,501,"Not implemented.")