Python Manual Benutzerhandbuch

Seite von 124
Module Caching
107
__servlet__ = ServletProxy()
Note that an instance of the servlet is created for each request. That is, unlike other similar systems
available for Python, an instance of a servlet object is not cached and reused. If you need to maintain
state between requests, such information should be factored out into a distinct service agent object.
Module Caching
In the case of the
PythonPlugin
object, when the file containing the actual servlet is read in, it is
compiled into Python byte code and cached. This means that a subsequent request against that servlet
will use the cached byte code and will not reread and recompile the file. So that is isn’t necessary to
stop and start the application if the file is changed, upon each subsequent request a check is made to
see if the file has since been modified. If the file has been modified, it will be reread and recompiled
ensuring that changes made to the file are visible.
Note that this mechanism will only detect if the actual servlet file has been modified. If that servlet file
imports other modules using the Python "
import
" command and it is those other modules which have
been changed, the cached servlet will still be used. This is acceptable where the other modules contain
core program logic on which other parts of the application are dependent, but not in the case where the
separate module contains a servlet base class defining the structure of a web page and it is the structure
of the web page which you wish to change.
To cater for this situation, a special mechanism is provided for importing of modules which define
servlet base classes or functionality related to the presentation of a web page. When this mechanism is
used, that the servlet file is dependent on the module is recorded and a servlet file will be reread and
recompiled, as will the module it depends on, when only the module had changed.
import os
import netsvc
cache = netsvc.ModuleCache()
directory = os.path.dirname(__file__)
_template = cache.importModule("_template",directory)
class HttpServlet(_template.PageServlet):
def writeContent(self):
self.writeln("Hi there.")
__servlet__ = HttpServlet
This means that the structure of a page can be defined in a common place, with each servlet file only
defining the content specific to that page. The module caching mechanism should however only be
used for this purpose. It is also recommended that for a particular module file, you not mix this mech-
anism and the standard Python import system, but use this system exclusively.