Servlet Plugins

The effect of this registration will be that whenever a file with extension ".py" is requested by a HTTP client, the plugin object will be executed as a callable object, with the HTTP session object and the name of the file being passed as arguments. In this case, the PythonPlugin object will import the file as if it is a Python module, obtain from it a reference to the HTTP servlet and then create an in- stance of the HTTP servlet to service the request.

The main difference when writing a servlet to be contained in a file and loaded in this way, as opposed to one which is hardwired into the actual application, is that it is necessary to provide a hook for cre- ating an instance of the servlet. This is done by providing a definition within the file of the symbol "__servlet__".

import netsvc

class HttpServlet(netsvc.HttpServlet): def processRequest(self):

if self.requestMethod() != "GET": self.sendError(400)

else:

self.sendResponse(200) self.sendHeader("Content-Type","text/plain") self.endHeaders()

self.sendContent("Hi there.") self.endContent()

__servlet__ = HttpServlet

In the simplest case, the symbol "__servlet__" can be defined to be a reference to the actual servlet type. The PythonPlugin object will execute "__servlet__" with the expectation it is a callable object, supplying it with a single argument of the HTTP session object. In the above case this will im- mediately result in an instance of the servlet being created.

An alternative might be that "__servlet__" be defined as a function. This would allow one of a number of servlets to be chosen based on specific criteria, such as the time of day or whether the serv- ice is operational.

def __servlet__(): return HttpServlet

If a servlet requires additional arguments to be supplied along with the HTTP session object, a proxy object could instead be defined which transparently supplies the additional arguments. For example, a servlet designed to facilitate directory browsing might be supplied the name of the directory in which the servlet file resided, with the servlet generating a directory listing of files contained in the directory.

class ServletProxy:

def __call__(self,session): directory = os.path.dirname(__file__) return BrowseServlet(session,directory)

106

Page 106
Image 106
Python Python Manual, 7.0pl5 manual 106