Application

The Application singleton.

Application is the main class that sets up and dispatches requests. This is done using the WSGI protocol, so an AppServer class is not needed and not contained in Webware for Python anymore. Application receives the input via WSGI and turns it into Transaction, HTTPRequest, HTTPResponse, and Session.

Settings for Application are taken from Configs/Application.config, which is used for many global settings, even if they aren’t closely tied to the Application object itself.

class Application.Application(path=None, settings=None, development=None)

Bases: ConfigurableForServerSidePath

The Application singleton.

Purpose and usage are explained in the module docstring.

__init__(path=None, settings=None, development=None)

Sets up the Application.

You can specify the path of the application working directory, a dictionary of settings to override in the configuration, and whether the application should run in development mode.

In the setting ‘ApplicationConfigFilename’ you can also specify a different location of the application configuration file.

addContext(name, path)

Add a context by named name, rooted at path.

This gets imported as a package, and the last directory of path does not have to match the context name. (The package will be named name, regardless of path).

Delegated to URLParser.ContextParser.

static addServletFactory(factory)

Add a ServletFactory.

Delegated to the URLParser.ServletFactoryManager singleton.

addShutDownHandler(func)

Add a shutdown handler.

Functions added through addShutDownHandler will be called when the Application is shutting down. You can use this hook to close database connections, clean up resources, save data to disk, etc.

callMethodOfServlet(trans, url, method, *args, **kw)

Call method of another servlet.

Call a method of the servlet referred to by the URL. Calls sleep() and awake() before and after the method call. Or, if the servlet defines it, then runMethodForTransaction is used (analogous to the use of runTransaction in forward).

The entire process is similar to forward, except that instead of respond, method is called (method should be a string, *args and **kw are passed as arguments to that method).

commandLineConfig()

Return the settings that came from the command-line.

These settings come via addCommandLineSetting().

config()

Return the configuration of the object as a dictionary.

This is a combination of defaultConfig() and userConfig(). This method caches the config.

configFilename()

The configuration file path.

configName()

Return the name of the configuration file without the extension.

This is the portion of the config file name before the ‘.config’. This is used on the command-line.

configReplacementValues()

Get config values that need to be escaped.

contexts()

Return a dictionary of context-name: context-path.

static createRequestForDict(requestDict)

Create request object for a given dictionary.

Create a request object (subclass of Request) given the raw dictionary as passed by the web server via WSGI.

The class of the request may be based on the contents of the dictionary (though only HTTPRequest is currently created), and the request will later determine the class of the response.

Called by dispatchRawRequest.

createSessionForTransaction(trans)

Get the session object for the transaction.

If the session already exists, returns that, otherwise creates a new session.

Finding the session ID is done in Transaction.sessionId.

createSessionWithID(trans, sessionID)

Create a session object with our session ID.

defaultConfig()

The default Application.config.

development()

Whether the application shall run in development mode

dispatchRawRequest(requestDict, strmOut)

Dispatch a raw request.

Dispatch a request as passed from the web server via WSGI.

This method creates the request, response, and transaction objects, then runs (via runTransaction) the transaction. It also catches any exceptions, which are then passed on to handleExceptionInTransaction.

errorPage(errorClass)

Get the error page url corresponding to an error class.

forward(trans, url)

Forward the request to a different (internal) URL.

The transaction’s URL is changed to point to the new servlet, and the transaction is simply run again.

Output is _not_ accumulated, so if the original servlet had any output, the new output will _replace_ the old output.

You can change the request in place to control the servlet you are forwarding to – using methods like HTTPRequest.setField.

handleException()

Handle exceptions.

This should only be used in cases where there is no transaction object, for example if an exception occurs when attempting to save a session to disk.

handleExceptionInTransaction(excInfo, trans)

Handle exception with info.

Handles exception excInfo (as returned by sys.exc_info()) that was generated by transaction. It may display the exception report, email the report, etc., handled by ExceptionHandler.ExceptionHandler.

handleMissingPathSession(trans)

Redirect requests without session info in the path.

If UseAutomaticPathSessions is enabled in Application.config we redirect the browser to an absolute url with SID in path http://gandalf/a/_SID_=2001080221301877755/Examples/ _SID_ is extracted and removed from path in HTTPRequest.py

This is for convenient building of webapps that must not depend on cookie support.

Note that we create an absolute URL with scheme and hostname because otherwise IIS will only cause an internal redirect.

handlePathSession(trans)

Handle the session identifier that has been found in the path.

handleUnnecessaryPathSession(trans)

Redirect request with unnecessary session info in the path.

This is called if it has been determined that the request has a path session, but also cookies. In that case we redirect to eliminate the unnecessary path session.

hasContext(name)

Checks whether context name exist.

hasSession(sessionId)

Check whether session sessionId exists.

hasSetting(name)

Check whether a configuration setting has been changed.

includeURL(trans, url)

Include another servlet.

Include the servlet given by the URL. Like forward, except control is ultimately returned to the servlet.

initErrorPage()

Initialize the error page related attributes.

initSessions()

Initialize all session related attributes.

initVersions()

Get and store versions.

Initialize attributes that stores the Webware version as both tuple and string. These are stored in the Properties.py files.

loadPlugIn(name, module)

Load and return the given plug-in.

May return None if loading was unsuccessful (in which case this method prints a message saying so). Used by loadPlugIns (note the s).

loadPlugIns()

Load all plug-ins.

A plug-in allows you to extend the functionality of Webware without necessarily having to modify its source. Plug-ins are loaded by Application at startup time, just before listening for requests. See the docs in PlugIn for more info.

makeDirs()

Make sure some standard directories are always available.

static name()

The name by which this was started. Usually Application.

numRequests()

Return the number of requests.

Returns the number of requests received by this application since it was launched.

outputEncoding()

Get the default output encoding of this application.

plugIn(name, default=<class 'MiscUtils.NoDefault'>)

Return the plug-in with the given name.

plugIns()

Return a dictionary of the plug-ins loaded by the application.

Each plug-in is a PlugIn object with an underlying Python package.

printConfig(dest=None)

Print the configuration to the given destination.

The default destination is stdout. A fixed with font is assumed for aligning the values to start at the same column.

printStartUpMessage()

Print a little intro to the activity log.

static readConfig(filename)

Read the configuration from the file with the given name.

Raises an UIError if the configuration cannot be read.

This implementation assumes the file is stored in utf-8 encoding with possible BOM at the start, but also tries to read as latin-1 if it cannot be decoded as utf-8. Subclasses can override this behavior.

registerShutDownHandler()

Register shutdown handler in various ways.

We want to make sure the shutdown handler is called, so that the application can save the sessions to disk and do cleanup tasks.

static removePathSession(trans)

Remove a possible session identifier from the path.

static resolveInternalRelativePath(trans, url)

Return the absolute internal path.

Given a URL, return the absolute internal URL. URLs are assumed relative to the current URL. Absolute paths are returned unchanged.

static returnServlet(servlet)

Return the servlet to its pool.

rootURLParser()

Accessor: the Root URL parser.

URL parsing (as defined by subclasses of URLParser.URLParser) starts here. Other parsers are called in turn by this parser.

runTransaction(trans)

Run transaction.

Executes the transaction, handling HTTPException errors. Finds the servlet (using the root parser, probably URLParser.ContextParser, to find the servlet for the transaction, then calling runTransactionViaServlet.

Called by dispatchRawRequest.

static runTransactionViaServlet(servlet, trans)

Execute the transaction using the servlet.

This is the awake/respond/sleep sequence of calls, or if the servlet supports it, a single runTransaction call (which is presumed to make the awake/respond/sleep calls on its own). Using runTransaction allows the servlet to override the basic call sequence, or catch errors from that sequence.

Called by runTransaction.

serverSidePath(path=None)

Get the server-side path.

Returns the absolute server-side path of the Webware application. If the optional path is passed in, then it is joined with the server side directory to form a path relative to the working directory.

session(sessionId, default=<class 'MiscUtils.NoDefault'>)

The session object for sessionId.

Raises KeyError if session not found and no default is given.

sessionCookiePath(trans)

Get the cookie path for this transaction.

If not path is specified in the configuration setting, the servlet path is used for security reasons, see: https://www.helpnetsecurity.com/2004/06/27/cookie-path-best-practice/

sessionName(_trans)

Get the name of the field holding the session ID.

Overwrite to make this transaction dependent.

sessionPrefix(_trans)

Get the prefix string for the session ID.

Overwrite to make this transaction dependent.

sessionTimeout(_trans)

Get the timeout (in seconds) for a user session.

Overwrite to make this transaction dependent.

sessions()

A dictionary of all the session objects.

setSetting(name, value)

Set a particular configuration setting.

setting(name, default=<class 'MiscUtils.NoDefault'>)

Return setting, using the server side path when indicated.

Returns the setting, filtered by self.serverSidePath(), if the name ends with Filename or Dir.

shutDown()

Shut down the application.

Called when the interpreter is terminated.

sigTerm(_signum, _frame)

Signal handler for terminating the process.

startSessionSweeper()

Start session sweeper.

Starts the session sweeper, Tasks.SessionTask, which deletes session objects (and disk copies of those objects) that have expired.

startTime()

Return the time the application was started.

The time is given as seconds, like time().

taskManager()

Accessor: TaskKit.Scheduler instance.

userConfig()

Return the user config overrides.

These settings can be found in the optional config file. Returns {} if there is no such file.

The config filename is taken from configFilename().

webwarePath()

Return the Webware path.

webwareVersion()

Return the Webware version as a tuple.

webwareVersionString()

Return the Webware version as a printable string.

writeActivityLog(trans)

Write an entry to the activity log.

Writes an entry to the script log file. Uses settings ActivityLogFilename and ActivityLogColumns.

writeExceptionReport(handler)

Write extra information to the exception report.

See ExceptionHandler for more information.

exception Application.EndResponse

Bases: Exception

End response exception.

Used to prematurely break out of the awake()/respond()/sleep() cycle without reporting a traceback. During servlet processing, if this exception is caught during awake() or respond() then sleep() is called and the response is sent. If caught during sleep(), processing ends and the response is sent.

__init__(*args, **kwargs)
args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.