Python Manual Benutzerhandbuch

Seite von 124
Servlet Plugins
108
Note that a module imported in this way can use the same mechanism to import further modules with
the dependence on those additional modules also being considered when the initial file is requested.
Be aware however, that if files are located on a different machine to that which the application is run-
ning on and the clocks are not sychronised properly, updates may not always be detected correctly.
Writing a Plugin
A plugin can be any callable object, so long as it accepts as arguments when called, a HTTP session
object and the name of a file which is the target of the request. The plugin may therefore be a type, a
function, or an object which overrides the "
__call__
" method. Which approach is used will depend
on whether state needs to be preserved between invocations of the plugin. If no state needs to be pre-
served, a simple function may be the most approrpiate.
def factory(session,file):
return netsvc.FileServlet(session,file)
filesrvr.plugin(".txt",factory)
If a HTTP servlet when being constructed takes the same arguments as those passed to the plugin, ie.,
the HTTP session object and the name of a file, the servlet itself might instead be registered as the
plugin.
filesrvr.plugin(".txt",netsvc.FileServlet)
Where state needs to be preserved, registration of an actual object instance which can hold the state,
may be a better approach.
class Plugin:
def __call__(self,session,file):
return netsvc.FileServlet(session,file)
filesrvr.plugin(".txt",Plugin())
Plugin Aliasing
When a plugin is registered, the filename extension specified must appear in the URL used by the
HTTP client when accessing that resource. This has the perhaps unwanted effect of exposing details
about how the web pages are implemented. This may limit to what extent you can easily change the
implementation later on, but may also give a malicious user ideas about how they may remotely break
into your system.
For these reasons, although a servlet file might be required to use the extension "
.py
", if that servlet
file always produces HTML, it may be preferable that that resource always be accessed by using a
"
.html
" extension. An ability to do this can also be useful in the case where a resource is initially
stored as a static file with a "
.html
" extension, but is later changed to be dynamically generated using