Module servlet :: Class Servlet
[show private | hide private]
[frames | no frames]

Class Servlet

Known Subclasses:
HTMLPage

Abstract base class for all mod_python servlets.

You must subclass this class implementing, minimally, respond, but you will probably want to subclass HTMLPage, which already subclasses Servlet and has many added features for generating HTML output.
Method Summary
  __init__(self)
Base constructor for all servlets.
  __str__(self)
Return a simple string representing an instance:
  add_cookie(self, cookie, value, **kw)
Wrapper around mod_python.Cookie.add_cookie().
  auth(self)
Basic HTTP authentication method.
  count(klass)
Get the count of requests for this servlet. (Class method)
  external_redirect(self, uri, permanently)
Send a redirect to the client via a Location HTTP header.
  flush(self)
Utilily method which immediately flushes all buffered output to the client.
  get_cookies(self, klass, **kw)
Wrapper around mod_python.Cookie.get_cookies().
  internal_redirect(self, uri)
Redirect internally.
  log(self, msg)
Utility method to write a message to the apache error log.
  prep(self)
This is the second user method called by the handler, after auth, prior to respond.
  raw_write(self, *args)
Like write, but all output is immediately flushed to the client and no string coercion is attempted on the arguments.
  respond(self)
This is the third user method called by the handler, after prep, before wrapup and is where the response is generated.
  sourcefilename(klass)
Get the filename of the source file for this servlet. (Class method)
  wrapup(self)
This is the fourth user method called by the handler, immediately after calling respond, before _finally.
  write(self, *args)
Utility method to write the arguments to the client.
  writeln(self, *args)
Like write, but in addition appends a newline to the output.
  __canonical_arg(self, arg)
Convert elements of query_vars and form_vars to a canonical form:
  __canonical_path_info(self, pi)
Private helper method to canonicalize the path info.
  __cleanup_session(self)
Clean up session use.
  __load_vars(self)
Set instance variables based on URI arguments and form variables.
  _auth_with_mapping(self, mapping)
Helper method to be used in auth.
  _finally(self)
This user method is the last called by the handler.
tuple of two strings _get_user_pw(self)
Helper method to be used in auth to retrieve username and password.
  _unauthorized(self)
Helper method to be used in auth.

Instance Variable Summary
str auth_realm: Specifies the realm for basic HTTP authentication.
str or None content_type: Specifies the content type of the servlet, i.e., "text/html".
instance of mod_python.util.FieldStorage form: User data sent with request via form or url.
list form_vars: This is the same as query_vars except these variables are only processed for POST requests.
float instantiated: Timestamp of when the servlet was instantiated.
list of unbound methods ok_methods_to_call: list of methods that can be called directly via a POST.
list of str path_info: req.path_info canonicalized as a list: stripping beginning and trailing "/" and splitting it on internal "/".
list query_vars: List of arguments to be searched for in form to be set as instance variables of the servlet.
  req: The apache request object.
bool reusable: Flag (default: True) indicating whether or not an instance of this servlet can be used for multiple requests.
instance of mod_python.Session.Session or None session: A Session (see the mod_python documentation for mod_python.Session.Session).
int session_timeout: Length of time, in seconds, until session times out.
bool use_session: If true, create (or reload) session for each request.

Instance Method Details

__init__(self)
(Constructor)

Base constructor for all servlets.

If subclasses override this method they must call this method for proper servlet initialization. For example:
 class MyServlet(Servlet):

     def __init__(self):
         Servlet.__init__(self)
         ...

__str__(self)
(Informal representation operator)

Return a simple string representing an instance:

"Servlet class name"

add_cookie(self, cookie, value='', **kw)

Wrapper around mod_python.Cookie.add_cookie(). See mod_python documentation for details.

auth(self)

Basic HTTP authentication method.

This method is the first user method called by the handler for each request, just before prep. It should return without exception if authorization is granted (the return value is ignored) or raise apache.SERVER_RETURN with apache.HTTP_UNAUTHORIZED as a value if authorization is denied. Typical implementation should use the _get_user_pw and _unauthorized helper methods:
   def auth(self):
       user, pw = self._get_user_pw()
       # test user, pw for authorization; if OK, return
       self._unauthorized()

See the source code for _auth_with_mapping for a simple implementation.

The base method is a no-op, i.e., no authentication is required.

external_redirect(self, uri, permanently=True)

Send a redirect to the client via a Location HTTP header.
Parameters:
uri - The URI to relocate to.
           (type=str)
permanently - If True (the default) reply with 301 (MOVED_PERMANENTLY, else 302 (MOVED_TEMPORARILY).
           (type=bool)
Returns:
Does not return.

flush(self)

Utilily method which immediately flushes all buffered output to the client.

If content_type has not already been written it will be.
Returns:
None

get_cookies(self, klass=<class 'mod_python.Cookie.Cookie'>, **kw)

Wrapper around mod_python.Cookie.get_cookies(). See mod_python documentaion for details.

internal_redirect(self, uri)

Redirect internally. This does not send a redirect to the client (see external_redirect), but redirects internally to the server. This is a wrapper around req.internal_redirect(); see mod_python documentation for details.
Parameters:
uri - The URI to relocate to.
           (type=str)
Returns:
Does not return.

log(self, msg)

Utility method to write a message to the apache error log.
Parameters:
msg - The message to be written to the log.
           (type=str or an object that can be converted into a str.)
Returns:
None

prep(self)

This is the second user method called by the handler, after auth, prior to respond.

It should be used as a means to prep the servlet for respond, e.g., opening data files, acquiring db connections, preprocessing form data, etc.

The return value is ignored by the handler.

If this method is implemented in a subclass, the superclass method must be called; e.g:
   class MyServlet(HTMLPage):
      ...

      def prep(self):
          HTMLPage.prep(self)
          ...
      ...

raw_write(self, *args)

Like write, but all output is immediately flushed to the client and no string coercion is attempted on the arguments.
Parameters:
args - tuple of arbitrary objects
Returns:
None

respond(self)

This is the third user method called by the handler, after prep, before wrapup and is where the response is generated. Typically, this will be by calls to write, writeln and/or raw_write. For example:
   def respond(self):
       self.writeln("Hello, world!")

For most developers, this method will not need to be written because the version implemented in HTMLPage is sufficient.

The base class implementation (which is called by HTMLPage.respond) allows for arbitrary methods to be called during form POSTs. See ok_methods_to_call.

This method must return True or False. If True, request processing will continue (and ultimately, content sent to the client), if False, a 204 response will be sent to the client (NO_CONTENT) and processing will stop.
Returns:
bool

wrapup(self)

This is the fourth user method called by the handler, immediately after calling respond, before _finally.

This method should be used to "tidy up" after a request, e.g., flush output data, create a log entry, etc.

The base method flushes output to the client. If overridden, this method should be called by the subclass if it does not call flush.

The return value is ignored by the handler.

write(self, *args)

Utility method to write the arguments to the client.

Each arg is coerced to a string and buffered for output. The output is sent to the client when flush is called explicitly or implicitly, when the handler is finished with the request.
Parameters:
args - tuple of arbitrary objects
Returns:
None

writeln(self, *args)

Like write, but in addition appends a newline to the output.
Parameters:
args - tuple of arbitrary objects
Returns:
None

__canonical_arg(self, arg)

Convert elements of query_vars and form_vars to a canonical form:
 (NAME, DEFAULT, CONVERSION)
Parameters:
arg - an element of query_vars or form_vars

__canonical_path_info(self, pi)

Private helper method to canonicalize the path info.

Splits pi and returns path_info as list.
Parameters:
pi - path_info
           (type=str)

__cleanup_session(self)

Clean up session use. If use_session is True and session is not None, save the session and delete it from the instance to allow for garbage collection.

__load_vars(self)

Set instance variables based on URI arguments and form variables.

See the documentation for query_vars and form_vars.

_auth_with_mapping(self, mapping)

Helper method to be used in auth. For example:
   def auth(self):
       self._auth_with_mapping(some_mapping)
where some_mapping is a mapping that supports the standard get method and where the keys are usernames and their values passwords.

_finally(self)

This user method is the last called by the handler. The previously called user methods (auth, prep, respond, wrapup) are called in a try clause of a try...finally statement. This method is called in the finally clause.

This method should be used as a final "tidy up" after a request: in case of an exception this method is guaranteed to be called whereas wrapup is not.

The base method saves the session and removes it from the instance (thus implicitly unlocking the session) if use_session is True. If overridden, this method must be called by the subclass.

The output of this method is ignored by the handler.

_get_user_pw(self)

Helper method to be used in auth to retrieve username and password.
Returns:
username, password
           (type=tuple of two strings)

_unauthorized(self)

Helper method to be used in auth.

Writes appropriate HTTP headers requesting authentication and raises an UNAUTHORIZED exception.

Class Method Details

count(klass)

Get the count of requests for this servlet.
Returns:
int

sourcefilename(klass)

Get the filename of the source file for this servlet.
Returns:
str

Instance Variable Details

auth_realm

Specifies the realm for basic HTTP authentication. Default: "Unspecified".
Type:
str
Value:
'Unspecified'                                                          

content_type

Specifies the content type of the servlet, i.e., "text/html". If it is not set (None) then it defaults to "text/plain". Default: None
Type:
str or None
Value:
None                                                                  

form

User data sent with request via form or url. For each request an instance of FieldStorage is created. Note: FieldStorage is created with blank values being ignored, ie, as if they did not exist.
Type:
instance of mod_python.util.FieldStorage

form_vars

This is the same as query_vars except these variables are only processed for POST requests. For all GET requests, these variables will be set to their default values.
Type:
list
Value:
[]                                                                     

instantiated

Timestamp of when the servlet was instantiated. This is stored as seconds since the epoch; see the python documentation for time.time().
Type:
float

ok_methods_to_call

list of methods that can be called directly via a POST. If the name of a form element looks like:
  _call_NAME()
and NAME is the name of an unbound method of the servlet and the method is listed in ok_methods_to_call, then that method will be called when the form is posted. The form element can also look like this:
  _call_SOME_METHOD(1,2,3)

and SOME_METHOD will be called with three arguments: 1, 2, 3.

See the tutorial that comes with the distribution for examples.
Type:
list of unbound methods
Value:
[]                                                                     

path_info

req.path_info canonicalized as a list: stripping beginning and trailing "/" and splitting it on internal "/".
Type:
list of str

query_vars

List of arguments to be searched for in form to be set as instance variables of the servlet. This processing occurs during the call to prep.

query_vars can be either a list of strings (the variable names) or a list of tuples of the form:
 (NAME, DEFAULT [,CONVERSION])

where NAME, a string, is the name of the variable and must be a legal python identifier; DEFAULT, must be a string, list or dict, is the default value for NAME if it does not appear in form, and, optionally, CONVERSION is a callable that can convert the string found in form (or DEFAULT) to an appropriate value and/or type.

When an element of query_var is just a string (not a tuple), this is equivalent to:
 (NAME, '')

That is, the default value for NAME, if not found in form, is an empty string.

If DEFAULT is a string, the value will be retrieved from form with a call to form.getfirst(). If DEFAULT is a list, the value will be retrieved by a call to form.getlist(). If DEFAULT is a dict, form will be searched for names with the pattern NAME[KEY] with calls to either getfirst() or getlist() depending on whether the default dict value is a list or string for that key.

All string values retrieved from form will be stripped of whitespace.

Example of query_vars:
    ["name",
     ("login", "", bool),
     ("items", []),
     ("map", {"foo" : "bar",
              "baz" : []})]

query_vars should be contrasted to form_vars. Where form_vars are only processed for POST requests, query_vars is processed for both POST and GET requests.

If installed, see the tutorial for a live demonstration of query_vars.
Type:
list
Value:
[]                                                                     

req

The apache request object.

reusable

Flag (default: True) indicating whether or not an instance of this servlet can be used for multiple requests. If False, instances will be recreated for every request of a servlet.
Type:
bool
Value:
True                                                                   

session

A Session (see the mod_python documentation for mod_python.Session.Session). A session object is created for each request if use_session is True. If use_session is False, this variable will be set to None.
Type:
instance of mod_python.Session.Session or None
Value:
None                                                                  

session_timeout

Length of time, in seconds, until session times out. Default: 30 minutes.
Type:
int
Value:
1800                                                                  

use_session

If true, create (or reload) session for each request. Default: False.
Type:
bool
Value:
False                                                                  

Generated by Epydoc 2.0 on Tue Mar 15 08:20:22 2005 http://epydoc.sf.net