API Documentation

brim

The Brim.Net Core Package.

It provides some reusable utility code and provides brimd, a launcher offering ease of deployment of WSGI applications (currently just using the Eventlet WSGI server), straight TCP and UDP socket applications, and maintaining background daemons.

brim Just contains __version__.
brim.conf Provides a simple way to work with configuration files.
brim.daemon_sample A sample implementation of a daemon.
brim.http Utilities for working with HTTP.
brim.httpform Module for working with HTTP Form POSTs iteratively.
brim.log Logging utilities for brimd.
brim.server The main module that implements the Brim.Net Core Server.
brim.service Provides functions useful for background services.
brim.tcp_echo A simple straight TCP socket application.
brim.udp_echo A simple straight UDP datagram application.
brim.util Miscellaneous classes and functions.
brim.wsgi_basic_auth A WSGI application that offers Basic Auth capabilities.
brim.wsgi_echo A simple WSGI application that just echoes the request body.
brim.wsgi_fs A WSGI application that simply serves up files from the file system.
brim.wsgi_stats Reports the brimd server stats as a JSON reponse.

brim.conf

Provides a simple way to work with configuration files.

This module can translate a ConfigParser-style configuration file into a simple dict, wrapping that with a Conf class providing convenient "get" functions that work much like dict's "get" method (return None or the default value provided if the section or option is missing) for various value types.

Simple Example Using read_conf():

from sys import exit

from brim.conf import read_conf

conf = read_conf(['/etc/myco/myapp.conf', '~/.myapp.conf'])
if not conf.files:
    exit('No configuration found.')
port = conf.get_int('server', 'port', 1234)
print 'Using port', port

By default, any error parsing the conf files or converting a value calls sys.exit with an explanatory message. But you can override this behavior by setting exit_on_read_exception to False and setting the Conf.error() method to your own method.

More Complex Example With Overrides:

from ConfigParser import Error
from sys import exit

from brim.conf import read_conf

try:
    conf = read_conf(
        ['/etc/myco/myapp.conf', '~/.myapp.conf'],
        exit_on_read_exception=False)
except Error as err:
    exit('Config read error: ' + str(err))
if not conf.files:
    exit('No configuration found.')

def custom_error(section, option, value, conversion_type, err):
    if not isinstance(section, basestring):
        section = '|'.join(section)  # Handle iter of sections
    raise Exception(
        'Configuration value [%s] %s of %r cannot be converted '
        'to %s.' % (section, option, value, conversion_type))

conf.error = custom_error
try:
    port = conf.get_int('server', 'port', 1234)
except Exception as err:
    exit('Config conversion error: ' + str(err))
print 'Using port', port

Another feature of read_conf is that if a conf file has a [brim] additional_confs setting, the files listed there are also be parsed. This lets an end user make a conf file to be included by one or more other conf files. Splitting configuration like this can make deployment to clusters easier. For example:

[brim]
additional_confs = /etc/common.conf "/another file.conf" ~/.common.conf
class brim.conf.Conf(store, files=None)

Bases: object

Wraps a configuration dict for richer access methods.

Within the dict store, each key is a section name and each value is another dict. Each section dict key is an option name and each value the actual value of the section/option within the conf. The list of file names the configuration was read from may optionally be stored.

Normally Conf instances are created with the global function read_conf() but you can construct Conf instances directly as well:

# Normally...
conf = read_conf(['/etc/myco/myapp.conf', '~/.myapp.conf'])

# Directly...
conf = Conf({
    'section1': {'option1.1': 'a', 'option1.2': 'b'},
    'section2': {'option2.1': 'c', 'option2.2': 'd'}})
Parameters:
  • store -- A dict representing the configuration, as described above.
  • files -- A list of file names the configuration was read from.
error(section, option, value, conversion_type, err)

Handles an error converting a section/option value.

This function is called when one of the "get" methods cannot convert a value. By default, this method calls sys.exit with an explanatory message, but you can override it by setting Conf.error to another method.

An example of overriding to raise an Exception:

def _error(section, option, value, conversion_type, err):
    raise Exception(
        'Configuration value [%s] %s of %r cannot be '
        'converted to %s.' %
        (section, option, value, conversion_type))

conf = read_conf(['some.conf'])
conf.error = _error

Note that the section parameter may have been given as an iterator of sections rather than just one section name.

Parameters:
  • section -- The section name (or an iterator of section names) within the conf that was read.
  • option -- The option name within the section that was read.
  • value -- The value read and failed conversion.
  • conversion_type -- The name of the type of conversion that failed, such as 'boolean', 'int', 'float', or path.
  • err -- The Exception that was raised, if any, during the conversion.
files = None

A list of source conf file names the conf was read from.

get(section, option, default=None)

Returns the value of the section/option.

get_bool(section, option, default)

Returns the boolean value of the section/option.

get_float(section, option, default)

Returns the float value of the section/option.

get_int(section, option, default)

Returns the int value of the section/option.

get_path(section, option, default=None)

Returns the path value of the section/option.

This is different that just retrieving a string only in that it calls os.path.expanduser on the value, translating ~/path and ~user/path constructs.

store = None

A dict containing the configuration information.

Each dict key is a section name and each value is another dict. Each section dict key is an option name and each value the actual value of the section/option within the conf.

brim.conf.FALSE_VALUES = ['0', 'f', 'false', 'n', 'no', 'off']

A list of lowercase string values that equate to False.

brim.conf.TRUE_VALUES = ['1', 'on', 't', 'true', 'y', 'yes']

A list of lowercase string values that equate to True.

brim.conf.read_conf(conf_files, exit_on_read_exception=True)

Returns a new Conf instance.

The new instance is based on the results from reading the conf_files into a ConfigParser.SafeConfigParser.

Note that if the parser does not have access to read a given file it acts as if it did not exist.

If a conf file has a [brim] additional_confs setting, the files listed there are also be parsed.

You may wish to check the Conf.files list to determine which files, if any, were read to form the Conf instance.

On a parser error, calls sys.exit with an explanatory message by default. If you set exit_on_read_exception to False, the ConfigParser.Error be raised instead.

Parameters:
  • conf_files -- An iterable of conf files or a string representing a single conf file to read and translate. Values in files further into the list override any values from prior files. File names may use the ~/filename or ~user/filename format and are expanded with os.path.expanduser.
  • exit_on_read_exception -- A boolean that indicates whether sys.exit should be called on error or if a ConfigParser.Error should be raised instead.
Returns:

A new Conf instance representing the configuration read from the conf_files.

brim.daemon_sample

A simple daemon that just logs a status line every so often.

This can be a good starting point for other daemons. See the source for what's implemented and why.

Configuration Options:

[daemon_sample]
call = brim.daemon_sample.DaemonSample
# interval = <seconds>
#   The number of seconds between each status line logged.
#   Default: 60

Standard configuration options for all daemons are also supported. See brimd.conf-sample for more information.

Stats Variables:

Name Type Description
iterations daemon Number of times a status line has been logged.
last_run daemon Timestamp when the last status line was logged.
start_time daemon Timestamp when the daemon was started. If the daemon had to be restarted, this timestamp will be updated with the new start time. This item is available with all daemons and set by the controlling brim.server.Subserver.
class brim.daemon_sample.DaemonSample(name, parsed_conf)

Bases: object

A simple daemon that just logs a status line every so often.

Parameters:
  • name -- The name of the daemon.
  • parsed_conf -- The result from parse_conf.
__call__(subserver, stats)

Logs a status line every so often.

This is the main entry point to the daemon. The brimd subserver will spawn a subprocess, create an instance of this daemon, and call this method. If the method exits for any reason, brimd will spawn a new subprocess, create a new daemon instance, and call this method again to ensure the daemon is always running.

The stats object will have at least the stat variables asked for in stats_conf(). This stats object will support at least the following methods:

get(name) Returns the int value of the stat named.
set(name, value) Sets the value of the stat named. The value will be treated as an unsigned integer.
incr(name) Increments the value of the stat named by 1.
Parameters:
  • subserver -- The brim.server.Subserver that is managing this daemon.
  • stats -- The shared memory statistics object as defined above.
Returns:

Hopefully never. If the method does return, the caller should create a new daemon instance and call this method again.

interval = None

The number of seconds between each status line logged.

name = None

The name of the daemon.

classmethod parse_conf(name, conf)

Translates the overall server configuration.

The conf is translated into a daemon-specific configuration dict suitable for passing as parsed_conf in the DaemonSample constructor.

See the overall docs of brim.daemon_sample for configuration options.

Parameters:
  • name -- The name of the daemon, indicates the daemon's section in the overall configuration for the server.
  • conf -- The brim.conf.Conf instance representing the overall configuration of the server.
Returns:

A dict suitable for passing as parsed_conf in the DaemonSample constructor.

classmethod stats_conf(name, parsed_conf)

Returns a list of (stat_name, stat_type) pairs.

These pairs specify the stat variables this daemon wants established in the stats instance passed to __call__().

Stats are often retrieved by users and utilities through WSGI apps like brim.wsgi_stats.WSGIStats.

See the overall docs of brim.daemon_sample for what stats are defined.

The available stat_types are:

daemon Indicates a daemon only stat. No overall stat will be reported.
sum Indicates an overall stat should be reported that is a sum of the stat from all daemons.
min Indicates an overall stat should be reported that is the smallest value of the stat from all daemons.
max Indicates an overall stat should be reported that is the largest value of the stat from all daemons.
Parameters:
  • name -- The name of the daemon, indicates the daemon's section in the overall configuration for the daemon server.
  • parsed_conf -- The result from parse_conf().
Returns:

A list of (stat_name, stat_type) pairs.

brim.http

Utilities for working with HTTP.

This isn't WebOb http://www.webob.org/ or Werkzeug http://werkzeug.pocoo.org but often it's enough and you should be able to upgrade easily to an alternative once you do need it.

There are classes for standard HTTP responses, such as HTTPNotFound for 404. These classes are all subclasses of HTTPException and therefore can be raised and caught as well as used as WSGI apps. The 2xx classes are all subclasses of HTTPOk (aka HTTPSuccess), 3xx subclasses of HTTPRedirection, 4xx subclasses of HTTPClientError, and 5xx subclasses of HTTPServerError. HTTPClientError and HTTPServerError also both subclass HTTPError.

Instead of a Request object, this package just provides some simpler classes and functions, like QueryParser and get_header_int(), and some replacement functions like quote() (it's Unicode-safe by using UTF8).

brim.http.CODE2NAME = {300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 307: 'Temporary Redirect', 100: 'Continue', 101: 'Switching Protocols', 102: 'Processing', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request-URI Too Long', 415: 'Unsupported Media Type', 416: 'Requested Range Not Satisfiable', 417: 'Expectation Failed', 422: 'Unprocessable Entity', 423: 'Locked', 424: 'Failed Dependency', 426: 'Upgrade Required', 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 207: 'Multi-Status', 208: 'Already Reported', 226: 'IM Used', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported', 506: 'Variant Also Negotiates', 507: 'Insufficient Storage', 508: 'Loop Detected', 510: 'Not Extended'}

Translates an HTTP status code to an English reason string.

exception brim.http.HTTPAccepted(body=None, headers=None)

Bases: brim.http.HTTPSuccess

exception brim.http.HTTPAlreadyReported(body=None, headers=None)

Bases: brim.http.HTTPSuccess

exception brim.http.HTTPBadGateway(body=None, headers=None)

Bases: brim.http.HTTPServerError

brim.http.HTTPBadRequest

alias of HTTPClientError

exception brim.http.HTTPClientError(body=None, headers=None, code=400)

Bases: brim.http.HTTPError

exception brim.http.HTTPConflict(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPContinue(body=None, headers=None, code=100)

Bases: brim.http.HTTPInformational

exception brim.http.HTTPCreated(body=None, headers=None)

Bases: brim.http.HTTPSuccess

exception brim.http.HTTPError(body=None, headers=None, code=500)

Bases: brim.http.HTTPException

exception brim.http.HTTPException(body=None, headers=None, code=500)

Bases: exceptions.Exception

Root class of all brim.http response classes.

If the body is None and the headers don't have a content-length or transfer-encoding the body is set to a reasonable default for the status code.

If the body has a length (as determined by hasattr(body, '__len__')) and the headers don't have a content-length or transfer-encoding, the content-length is set to the body's length.

If the headers have no content-type, text/plain is used by default.

Parameters:
  • body -- The body of the response.
  • headers -- A dict of the headers to include in the response.
  • code -- The HTTP response code to give; defaults to 500.
__call__(env, start_response)

WSGI callable.

exception brim.http.HTTPExpectationFailed(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPFailedDependency(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPForbidden(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPFound(body=None, headers=None, code=302)

Bases: brim.http.HTTPRedirection

exception brim.http.HTTPGatewayTimeout(body=None, headers=None)

Bases: brim.http.HTTPServerError

exception brim.http.HTTPGone(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPHTTPVersionNotSupported(body=None, headers=None)

Bases: brim.http.HTTPServerError

exception brim.http.HTTPIMUsed(body=None, headers=None)

Bases: brim.http.HTTPSuccess

exception brim.http.HTTPInformational(body=None, headers=None, code=100)

Bases: brim.http.HTTPException

exception brim.http.HTTPInsufficientStorage(body=None, headers=None)

Bases: brim.http.HTTPServerError

brim.http.HTTPInternalServerError

alias of HTTPServerError

exception brim.http.HTTPLengthRequired(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPLocked(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPLoopDetected(body=None, headers=None)

Bases: brim.http.HTTPServerError

exception brim.http.HTTPMethodNotAllowed(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPMovedPermanently(body=None, headers=None, code=301)

Bases: brim.http.HTTPRedirection

exception brim.http.HTTPMultiStatus(body=None, headers=None)

Bases: brim.http.HTTPSuccess

brim.http.HTTPMultipleChoices

alias of HTTPRedirection

exception brim.http.HTTPNoContent(body=None, headers=None)

Bases: brim.http.HTTPSuccess

exception brim.http.HTTPNonAuthoritativeInformation(body=None, headers=None)

Bases: brim.http.HTTPSuccess

exception brim.http.HTTPNotAcceptable(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPNotExtended(body=None, headers=None)

Bases: brim.http.HTTPServerError

exception brim.http.HTTPNotFound(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPNotImplemented(body=None, headers=None)

Bases: brim.http.HTTPServerError

exception brim.http.HTTPNotModified(body=None, headers=None, code=304)

Bases: brim.http.HTTPRedirection

brim.http.HTTPOK

alias of HTTPSuccess

brim.http.HTTPOk

alias of HTTPSuccess

exception brim.http.HTTPPartialContent(body=None, headers=None)

Bases: brim.http.HTTPSuccess

exception brim.http.HTTPPaymentRequired(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPPreconditionFailed(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPProcessing(body=None, headers=None, code=102)

Bases: brim.http.HTTPInformational

exception brim.http.HTTPProxyAuthenticationRequired(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPRedirection(body=None, headers=None, code=300)

Bases: brim.http.HTTPException

exception brim.http.HTTPRequestEntityTooLarge(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPRequestTimeout(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPRequestURITooLong(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPRequestedRangeNotSatisfiable(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPResetContent(body=None, headers=None)

Bases: brim.http.HTTPSuccess

brim.http.HTTPResponse

alias of HTTPException

exception brim.http.HTTPSeeOther(body=None, headers=None, code=303)

Bases: brim.http.HTTPRedirection

exception brim.http.HTTPServerError(body=None, headers=None, code=500)

Bases: brim.http.HTTPError

exception brim.http.HTTPServiceUnavailable(body=None, headers=None)

Bases: brim.http.HTTPServerError

exception brim.http.HTTPSuccess(body=None, headers=None, code=200)

Bases: brim.http.HTTPException

exception brim.http.HTTPSwitchingProtocols(body=None, headers=None, code=101)

Bases: brim.http.HTTPInformational

exception brim.http.HTTPTemporaryRedirect(body=None, headers=None, code=307)

Bases: brim.http.HTTPRedirection

exception brim.http.HTTPUnauthorized(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPUnprocessableEntity(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPUnsupportedMediaType(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPUpgradeRequired(body=None, headers=None)

Bases: brim.http.HTTPClientError

exception brim.http.HTTPUseProxy(body=None, headers=None, code=305)

Bases: brim.http.HTTPRedirection

exception brim.http.HTTPVariantAlsoNegotiates(body=None, headers=None)

Bases: brim.http.HTTPServerError

class brim.http.QueryParser(query_string=None)

Bases: object

Provides convenient retrieval methods for query parameter values.

Parameters:query_string -- The HTTP query string, such as in WSGI's env['QUERY_STRING']. If using something other than WSGI's QUERY_STRING, be sure to not include the question mark that separates the path?query string as it would be translated as the first character of the first parameter.
get(name, default=None, last_only=True)

Returns the value of the query parameter.

Parameters:
  • name -- The name of the query parameter to retrieve.
  • default -- The default value if the parameter does not exist. If default is None, the parameter is considered required and HTTPBadRequest is raised if the parameter is missing.
  • last_only -- If True (the default), only the last value of the parameter is returned if the parameter is specified multiple times. If False, all values are returned in a list (even if there is only one value).
get_bool(name, default=None)

Returns the boolean value of the query parameter.

The parameter value is checked against known brim.conf.TRUE_VALUES and brim.conf.FALSE_VALUES for translation and raises HTTPBadRequest if the value cannot be translated.

If the parameter is included in the query string but has no value then the value of not default is returned.

Parameters:
  • name -- The name of the query parameter to retrieve.
  • default -- The default value if the parameter does not exist. If default is None, the parameter is considered required and HTTPBadRequest is raised if the parameter is missing.
get_float(name, default=None)

Returns the float value of the query parameter.

If the value cannot be translated to a float, raises HTTPBadRequest.

Parameters:
  • name -- The name of the query parameter to retrieve.
  • default -- The default value if the parameter does not exist or has no value. If default is None, the parameter is be considered required and HTTPBadRequest is raised if the parameter is missing.
get_int(name, default=None)

Returns the int value of the query parameter.

If the value cannot be translated to an int, raises HTTPBadRequest.

Parameters:
  • name -- The name of the query parameter to retrieve.
  • default -- The default value if the parameter does not exist or has no value. If default is None, the parameter is be considered required and HTTPBadRequest is raised if the parameter is missing.
brim.http.get_header(env, name, default=None)

Returns the value of an HTTP header.

Parameters:
  • env -- The standard WSGI env to read from.
  • name -- The name of the header to retrieve.
  • default -- If specified, the default value if the header cannot be found. If default is None, the header value is considered required and HTTPBadRequest is raised if the header is missing.
brim.http.get_header_bool(env, name, default=None)

Returns the boolean value of an HTTP header.

The header value is checked against known brim.conf.TRUE_VALUES and brim.conf.FALSE_VALUES for translation and raises HTTPBadRequest if the value cannot be translated.

Parameters:
  • env -- The standard WSGI env to read from.
  • name -- The name of the header to retrieve.
  • default -- If specified, the default value if the header cannot be found. If default is None, the header value is considered required and HTTPBadRequest is raised if the header is missing.
brim.http.get_header_float(env, name, default=None)

Returns the float value of an HTTP header.

If the value cannot be translated to a float, raises HTTPBadRequest.

Parameters:
  • env -- The standard WSGI env to read from.
  • name -- The name of the header to retrieve.
  • default -- If specified, the default value if the header cannot be found. If default is None, the header value is considered required and HTTPBadRequest is raised if the header is missing.
brim.http.get_header_int(env, name, default=None)

Returns the int value of an HTTP header.

If the value cannot be translated to an int, raises HTTPBadRequest.

Parameters:
  • env -- The standard WSGI env to read from.
  • name -- The name of the header to retrieve.
  • default -- If specified, the default value if the header cannot be found. If default is None, the header value is considered required and HTTPBadRequest is raised if the header is missing.
brim.http.quote(value, safe='/')

Patched version of urllib.quote that UTF8 encodes unicode.

brim.httpform

Module for working with HTTP Form POSTs iteratively.

Warning

This is an early version of this module. It has no tests, limited documentation, and is subject to major changes.

Provides tools for parsing an HTTP Form POST without reading the whole thing into memory first. Many thanks to Michael Barton for the original prototype which I mangled into OpenStack Swift's formpost middleware and then into this module.

The basic usage is to iterate over iter_form results, which are rfc822.Message instances:

from brim.httpform import iter_form, parse_attrs

def wsgi_app(env, start_response):
    for message in iter_form(env):
        body = message.fp.read()
        value, attrs = \
            parse_attrs(message.getheader('content-disposition'))
        if value != 'form-data':
            continue
        if 'filename' in attrs:
            filevarname = attrs['name']
            filename = attrs['filename']
            filecontent = body
        else:
            varname = attrs['name']
            varvalue = body

See also the simple test at the end of the source file.

class brim.httpform.CappedFileLikeObject(fp, max_file_size)

Bases: object

Reads a limited amount from a file-like object.

A file-like object wrapping another file-like object that raises an EOFError if the amount of data read exceeds a given max_file_size.

This is useful to cap the form data size accepted:

for message in iter_form(env):
    try:
        content = CappedFileLikeObject(message.fp, 4096).read()
    except EOFError:
        raise HTTPRequestEntityTooLarge(
            'Max form part size is 4096.\n')
read(size=None)
readline()
exception brim.httpform.FormInvalid

Bases: exceptions.Exception

brim.httpform.iter_form(env, read_chunk_size=4096)

Yields messages for an HTTP Form POST.

Parses an HTTP Form POST and yields rfc822.Message instances for each form part. See the overview module brim.httpform for usage.

Parameters:
  • env -- The WSGI environment for the incoming request.
  • read_chunk_size -- The maximum amount to read at once from the incoming request.
Returns:

A generator yielding rfc822.Messages; be sure to fully read from the message.fp file-like object before continuing to the next message of the generator.

brim.httpform.parse_attrs(header)

Returns (value, attr_dict) for an HTTP attr header.

Given a header like:

Content-Disposition: form-data; name="abc"; filename="test.html"

Returns:

("form-data", {"name": "abc", "filename": "test.html"})

Example usage with an rfc822.Message:

value, attrs = parse_attrs(
    message.getheader('content-disposition'))

brim.log

Provides logging utilities for brimd.

Normally you don't need to use this module directly as the active logger itself is passed via the WSGI env['brim.logger'] value.

brim.log.get_logger(route, name, level, facility, console)

Returns a Logger based on the information given.

Parameters:
  • route -- The str log route, which is often the same as the name but does not have to be. Think of this as the key for the logger in source code.
  • name -- The str log name, this is the name sent to the underlying log system. Think of this as the display name for the logger.
  • level -- The str log level for which any records at or above the level will be sent to the underlying log system. Any records below the level will be discarded.
  • facility -- If the underlying log system supports it, such as syslog, this str facility value can help direct the system where to store the records.
  • console -- If set True, the underlying log system will simply be to sys.stdout. This can be useful for debugging. Normally you'll want to set this False so the log records are sent to syslog.
brim.log.NOTICE = 25

An additional log level patched into the standard logging levels.

This level is to be used for logging HTTP requests only so that it can be easily filtered on to form access logs.

brim.log.sysloggable_excinfo(*excinfo)

Returns exception information as a string for syslog.

The returned string will have no newlines, the exception type and message first in case the line is truncated, and anything else deemed to make it nicer for delivery to syslog.

Parameters:excinfo -- The exception info (exctype, value, traceback) such as returned with sys.exc_info.

brim.server

The main module that implements the Brim.Net Core Server.

Normally you don't directly use this module but instead configure and run brimd.

See brimd.conf-sample for configuration options.

brim.server.DEFAULT_CONF_FILES = ['/etc/brimd.conf', '~/.brimd.conf']

The list of default conf files to use when none are specified.

class brim.server.DaemonsSubserver(server, name='daemons')

Bases: brim.server.Subserver

Subserver for daemons.

Created for a [daemons] config section to hold the attributes specific to that subconfig.

Parameters:server -- The parent brim.server.Server.
brim.server.HTTP_CLIENT_DISCONNECT = 499

The status code for requests terminated early by the client (499).

class brim.server.IPSubserver(server, name)

Bases: brim.server.Subserver

Base class for "raw" IP based subservers.

Created for each [wsgi], [wsgi2], etc., [tcp], [tcp2], etc. [udp], [udp2], etc. config section to hold the attributes specific to that subconfig.

Parameters:
  • server -- The parent brim.server.Server.
  • name -- The name of the subserver ('wsgi', 'tcp', 'udp', etc.)
brim.server.PID_WAIT_TIME = 15

The seconds to wait for a PID to disappear after signaling.

class brim.server.Server(args=None, stdin=None, stdout=None, stderr=None)

Bases: object

The main entry point for the Brim.Net Core Server, brimd.

Few daemons or apps need to access this directly.

Parameters:
  • args -- Command line arguments for the server, without the process name. Defaults to sys.argv[1:]
  • stdin -- The file-like object to treat as standard input. Defaults to sys.stdin.
  • stdout -- The file-like object to treat as standard output. Defaults to sys.stdout.
  • stderr -- The file-like object to treat as standard error. Defaults to sys.stderr.
main()

Performs the brimd actions (start, stop, shutdown, etc.).

The action is determined by the command line arguments given in the constructor. Usage can be read from brimd --help.

Returns:An integer exit code suitable for returning with sys.exit.
class brim.server.Subserver(server, name)

Bases: object

Base class for brimd subservers (wsgi, tcp, udp, daemons).

Created for each [wsgi], [wsgi2], etc., [tcp], [tcp2], etc. [udp], [udp2], etc., and [daemons] config section to hold the attributes specific to that subconfig.

Parameters:
  • server -- The parent brim.server.Server.
  • name -- The name of the subserver ('wsgi', 'tcp', 'udp', 'daemons', etc.)
json_dumps = None

The json.dumps compatible function configured.

WSGI apps can also access this via env['brim.json_dumps'].

json_loads = None

The json.loads compatible function configured.

WSGI apps can also access this via env['brim.json_loads'].

logger = None

The logger in use by this subserver.

WSGI apps can also access this via env['brim.logger'].

server = None

The parent brim.server.Server of this subserver.

class brim.server.TCPSubserver(server, name)

Bases: brim.server.IPSubserver

Subserver for TCP.

Created for each [tcp], [tcp2], [tcp3] config section to hold the attributes specific to that subconfig.

Parameters:
  • server -- The parent brim.server.Server.
  • name -- The name of the subserver ('tcp', 'tcp2', 'tcp3', etc.)
class brim.server.UDPSubserver(server, name)

Bases: brim.server.IPSubserver

Subserver for UDP.

Created for each [udp], [udp2], [udp3] config section to hold the attributes specific to that subconfig.

Parameters:
  • server -- The parent brim.server.Server.
  • name -- The name of the subserver ('udp', 'udp2', 'udp3', etc.)
class brim.server.WSGISubserver(server, name)

Bases: brim.server.IPSubserver

Subserver for WSGI.

Created for each [wsgi], [wsgi2], [wsgi3] config section to hold the attributes specific to that subconfig. Few WSGI apps need to access this directly, but some like brim.wsgi_stats.WSGIStats do. From a WSGI app, you can gain access to the handling WSGISubserver through env['brim'].

Parameters:
  • server -- The parent brim.server.Server.
  • name -- The name of the subserver ('wsgi', 'wsgi2', 'wsgi3', etc.)
__call__(env, start_response)

Default WSGI application that responds with 404 Not Found.

clone_env(env)

Returns a new WSGI environment dictionary.

This can be useful when wanting to issue an additional request through get_response. For example:

...
def __call__(self, env, start_response):
    newenv = env['brim'].clone_env(env)
    newenv['REQUEST_METHOD'] = 'HEAD'
    newenv['PATH_INFO'] = '/new/path'
    newenv['wsgi.input'] = StringIO()
    status_line, headers_iteritems, excinfo, content_iter = \
        newenv['brim'].get_response(newenv)
    ...

The values copied are:

brim The Subserver handling the request.
brim.json_dumps The json.dumps compatible function configured.
brim.json_loads The json.loads compatible function configured.
brim.logger The logger configured.
brim.stats The stats object for tracking worker stats. See the overall package documentation for more information.
brim.txn The transaction id for the request. You should generally not change this as keeping the same txn for the main request and all its subrequests is useful when debugging.
SERVER_NAME Standard WSGI value.
SERVER_PORT Standard WSGI value.
SERVER_PROTOCOL Standard WSGI value.

Additional values created are:

HTTP_REFERER This is set to the REQUEST_PATH from the original env.
HTTP_USER_AGENT This is set to 'clone_env'. It is recommended to change this to something referring to your application for easier debugging later.
get_response(env, next_app=None)

Performs a WSGI request.

This is useful for WSGI apps that wish to perform subrequests. For example:

...
def __call__(self, env, start_response):
    newenv = env['brim'].clone_env(env)
    newenv['REQUEST_METHOD'] = 'HEAD'
    newenv['PATH_INFO'] = '/new/path'
    newenv['wsgi.input'] = StringIO()
    status_line, headers_iteritems, excinfo, content_iter = \
        newenv['brim'].get_response(newenv)
    ...

By default, the request goes to the front of the configured WSGI pipeline; however, you can also specify a different WSGI pipeline to travel through with the next_app arg. For example, auth middleware might want its subrequests to only travel from the next app in its pipeline onward.

Parameters:
  • env -- The WSGI environment of the request.
  • next_app -- Optional; indicates the next WSGI app to send the request through rather than the entire WSGI pipeline.
Returns:

The response as (status_line, headers_iteritems, excinfo, content_iter).

brim.server.main()

brimd script entry point.

brim.service

Provides functions useful for background services.

brim.service.capture_exceptions_stdout_stderr(exceptions=None, stdout_func=None, stderr_func=None)

Captures uncaught exceptions and redirects them.

This will redirect uncaught exceptions and redirect them to the exceptions function and captures standard output and error and redirects that data to the stdout_func and stderr_func functions. The original standard output and error files will be closed so that no output can come from your program to these streams. This is useful when writing background daemons that often have no connected console.

The exceptions function will be called with (exctype, value, traceback).

The stdout_func and stderr_func functions will be called with (str).

brim.service.droppriv(user, group=None, umask=18)

Drops the privileges of the running process.

Drops privileges to the user, group, and umask given, changes the process to session leader, and changes working directories to /. If a group is not given, the user's default group will be used. Will raise an Exception with an explanatory message if the user or group cannot be found or if permission is denied while attempting the switch.

Parameters:
  • user -- The user to switch to.
  • group -- The group to switch to; defaults to the default group of the user.
  • umask -- The umask to set; defaults 0022.
brim.service.get_listening_tcp_socket(ip, port, backlog=4096, retry=30, certfile=None, keyfile=None, style=None)

Returns a bound socket.socket for accepting TCP connections.

The socket will be bound to the given ip and tcp port with other optional parameters.

Parameters:
  • ip -- The ip address to listen on. '' and '*' are translated to '0.0.0.0' which will listen on all configured addresses.
  • port -- The tcp port to listen on.
  • backlog -- The amount of system queued connections allowed.
  • retry -- The number seconds to keep trying to bind the socket, in case there's another process bound but exiting soon. This allows near zero-downtime process handoffs as you start the new one and kill the old.
  • certfile -- The certificate file if you wish the socket to be ssl wrapped (see ssl.wrap_socket).
  • keyfile -- The key file if you wish the socket to be ssl wrapped (see ssl.wrap_socket).
  • style -- The libraries you'd like to use in creating the socket. The default will use the standard Python libraries. 'eventlet' is recognized and will use the Eventlet libraries. Other styles may added in the future.
brim.service.get_listening_udp_socket(ip, port, retry=30, style=None)

Returns a bound socket.socket for accepting UDP datagrams.

The socket will be bound to the given ip and tcp port with other optional parameters.

Parameters:
  • ip -- The ip address to listen on. '' and '*' are translated to '0.0.0.0' which will listen on all configured addresses.
  • port -- The udp port to listen on.
  • retry -- The number seconds to keep trying to bind the socket, in case there's another process bound but exiting soon. This allows near zero-downtime process handoffs as you start the new one and kill the old.
  • style -- The libraries you'd like to use in creating the socket. The default will use the standard Python libraries. 'Eventlet' is recognized and will use the Eventlet libraries. Other styles may added in the future.
brim.service.signum2str(signum)

Translates a signal number to a str.

Example:

>>> print signum2str(1)
SIGHUP
Parameters:signum -- The signal number to convert.
Returns:A str representing the signal.
brim.service.sustain_workers(workers_desired, worker_func, logger=None)

Starts and maintains a set of subprocesses.

For each worker started, it will run the worker_func. If a subprocess exits without being requested to, it will be restarted and the worker_func called again.

sustain_workers will not return until signaled to do so with SIGHUP or SIGTERM to the main process. These signals will be relayed to the subprocesses as well.

SIGHUP generally means the processes should exit as gracefully as possible. For instance, a web server might exit after it completes any requests already in progress.

SIGTERM generally means the processes should exit immediately, canceling anything they may have been doing at the time.

If workers_desired is 0, a special "inproc" mode will be activated where just the worker_func will be called and then sustain_workers will return. This can be useful for debugging.

See the source of brim.server.Server for a good example of how to use sustain_workers.

Parameters:
  • workers_desired -- The number of subprocesses desired to be maintained. If 0, no subprocesses will be made and worker_func will simply be called and then sustain_workers will return.
  • worker_func -- The function to be called by each subprocess once it starts. worker_func should not return except on catastrophic error or when signaled to do so. If worker_func exits without being signaled, another subprocess will be started and the function called again.
  • logger -- If set, debug information will be sent to this logging.Logger instance.

brim.tcp_echo

Contains a simple straight TCP socket application.

The application just echoes any incoming data back. This is a good starting point for other TCP applications. See the source for what's implemented and why.

Configuration Options:

[tcp_echo]
call = brim.tcp_echo.TCPEcho
# chunk_read = <bytes>
#   The maximum number of bytes to read before echoing it
#   back. Default: 65536

Standard configuration options for all TCP apps are also supported. See brimd.conf-sample for more information.

Stats Variables:

Name Type Description
byte_count sum Number of bytes read from clients.
connection_count sum The number of connections made to this app.
start_time worker Timestamp when the app was started. If the app had to be restarted, this timestamp will be updated with the new start time. This item is available with all apps and set by the controlling brim.server.Subserver.
class brim.tcp_echo.TCPEcho(name, parsed_conf)

Bases: object

A simple straight TCP socket application.

The application just echoes any incoming data back. This is a good starting point for other TCP applications. See the source for what's implemented and why.

Parameters:
  • name -- The name of the app.
  • parsed_conf -- The conf result from parse_conf().
__call__(subserver, stats, sock, ip, port)

Simply echo the incoming data back.

This is the main entry point to the daemon. The brimd subserver will spawn a subprocess, listen on a TCP endpoint, create an instance of this app, and then call this method for each incoming connection. If the app raises an Exception, a new instance of the app will be created and handed future connections.

The stats object will have at least the stat variables asked for in stats_conf(). This stats object will support at least the following methods:

get(name) Returns the int value of the stat named.
set(name, value) Sets the value of the stat named. The value will be treated as an unsigned integer.
incr(name) Increments the value of the stat named by 1.
Parameters:
  • subserver -- The brim.server.Subserver that is managing this app.
  • stats -- The shared memory statistics object as defined above.
  • sock -- The just connected socket.
chunk_read = None

The most to read from the client at once.

name = None

The name of the app.

classmethod parse_conf(name, conf)

Translates the overall server configuration.

The conf is translated into a daemon-specific configuration dict suitable for passing as parsed_conf in the TCPEcho constructor.

See the overall docs of brim.tcp_echo for configuration options.

Parameters:
  • name -- The name of the app, indicates the app's section in the overall configuration for the server.
  • conf -- The brim.conf.Conf instance representing the overall configuration of the server.
Returns:

A dict suitable for passing as parsed_conf in the TCPEcho constructor.

classmethod stats_conf(name, parsed_conf)

Returns a list of (stat_name, stat_type) pairs.

These pairs specify the stat variables this app wants established in the stats instance passed to __call__().

Stats are often retrieved by users and utilities through WSGI apps like brim.wsgi_stats.WSGIStats.

See the overall docs of brim.tcp_echo for what stats are defined.

The available stat_types are:

worker Indicates a worker only stat. No overall stat will be reported.
sum Indicates an overall stat should be reported that is a sum of the stat from all workers.
min Indicates an overall stat should be reported that is the smallest value of the stat from all workers.
max Indicates an overall stat should be reported that is the largest value of the stat from all workers.
Parameters:
  • name -- The name of the app, indicates the app's section in the overall configuration for the daemon server.
  • parsed_conf -- The result from parse_conf().
Returns:

A list of (stat_name, stat_type) pairs.

brim.udp_echo

Contains a simple straight UDP datagram application.

The application just echoes any incoming data back. This is a good starting point for other UDP applications. See the source for what's implemented and why.

Configuration Options:

[udp_echo]
call = brim.udp_echo.UDPEcho

Standard configuration options for all UDP apps are also supported. See brimd.conf-sample for more information.

Stats Variables:

Name Type Description
byte_count sum Number of bytes read from clients.
datagram_count sum The number of datagrams received.
start_time worker Timestamp when the app was started. If the app had to be restarted, this timestamp will be updated with the new start time. This item is available with all apps and set by the controlling brim.server.Subserver.
class brim.udp_echo.UDPEcho(name, parsed_conf)

Bases: object

A simple straight UDP socket application.

The application just echoes any incoming data back. This is a good starting point for other UDP applications. See the source for what's implemented and why.

Parameters:
  • name -- The name of the app.
  • parsed_conf -- The conf result from parse_conf().
__call__(subserver, stats, sock, datagram, ip, port)

Simply echo the incoming data back.

This is the main entry point to the daemon. The brimd subserver will spawn a subprocess, listen on a UDP endpoint, create an instance of this app, and then call this method for each incoming datagram. If the app raises an Exception, a new instance of the app will be created and handed future datagrams.

The stats object will have at least the stat variables asked for in stats_conf(). This stats object will support at least the following methods:

get(name) Returns the int value of the stat named.
set(name, value) Sets the value of the stat named. The value will be treated as an unsigned integer.
incr(name) Increments the value of the stat named by 1.
Parameters:
  • subserver -- The brim.server.Subserver that is managing this app.
  • stats -- The shared memory statistics object as defined above.
  • sock -- The socket associated with the datagram; useful for replying back using sendto.
  • datagram -- The just received datagram.
  • ip -- The remote IP address.
  • port -- The remote IP port.
name = None

The name of the app.

classmethod parse_conf(name, conf)

Translates the overall server configuration.

The conf is translated into a daemon-specific configuration dict suitable for passing as parsed_conf in the UDPEcho constructor.

See the overall docs of brim.udp_echo for configuration options.

Parameters:
  • name -- The name of the app, indicates the app's section in the overall configuration for the server.
  • conf -- The brim.conf.Conf instance representing the overall configuration of the server.
Returns:

A dict suitable for passing as parsed_conf in the UDPEcho constructor.

classmethod stats_conf(name, parsed_conf)

Returns a list of (stat_name, stat_type) pairs.

These pairs specify the stat variables this app wants established in the stats instance passed to __call__().

Stats are often retrieved by users and utilities through WSGI apps like brim.wsgi_stats.WSGIStats.

See the overall docs of brim.udp_echo for what stats are defined.

The available stat_types are:

worker Indicates a worker only stat. No overall stat will be reported.
sum Indicates an overall stat should be reported that is a sum of the stat from all workers.
min Indicates an overall stat should be reported that is the smallest value of the stat from all workers.
max Indicates an overall stat should be reported that is the largest value of the stat from all workers.
Parameters:
  • name -- The name of the app, indicates the app's section in the overall configuration for the daemon server.
  • parsed_conf -- The result from parse_conf().
Returns:

A list of (stat_name, stat_type) pairs.

brim.util

Miscellaneous classes and functions.

exception brim.util.LockPathTimeout

Bases: exceptions.Exception

Raised by lock_path() if its timeout is reached.

brim.util.lock_path(*args, **kwds)

A context manager that attempts to gain an advisory lock.

The advisory lock is attempted for the path given within the timeout given. Raises LockPathTimeout if time expires before gaining the lock. If the lock is obtained, True is yielded and the lock relinquished when the context ends.

For example:

with lock_path(path, timeout):
    # do things inside path knowing others using the same
    # advisory locking mechanism will be blocked until you're
    # done.
Parameters:
  • path -- The path to gain an advisory lock on.
  • timeout -- The number of seconds to wait to gain the lock before raising LockPathTimeout.
brim.util.make_dirs(path, mode=511)

os.makedirs but ignoring errors due to the path already existing.

Parameters:
  • path -- The path to create a directory and all parent directories for.
  • mode -- The permissions mode (masked with the current umask) to create new directories with; defaults to 0o777.

os.unlink but ignoring errors due to the path already not existing.

brim.wsgi_basic_auth

A WSGI application that offers Basic Auth capabilities.

Warning

This is an early version of this module. It has no tests, limited documentation, and is subject to major changes.

Warning

This is HTTP Basic Auth, so the password will be transmitted in the clear. You definitely should be using SSL when using Basic Auth.

Note

Requires the bcrypt package https://pypi.python.org/pypi/py-bcrypt

Configuration Options:

[basic-auth]
call = brim.wsgi_basic_auth.WSGIBasicAuth
# auth_path = <path>
#   The local file path to the auth details. This file should be
#   plain text, one user per line, with each line a user name
#   followed by whitespace and then the bcrypt password entry for
#   the user. You can obtain the bcrypt password entry with the
#   following:
#       $ python -c '
#       > import bcrypt
#       > print bcrypt.hashpw("secret", bcrypt.gensalt())'
#   The file will automatically be reloaded if changed within five
#   minutes.
class brim.wsgi_basic_auth.WSGIBasicAuth(name, parsed_conf, next_app)

Bases: object

A WSGI application that offers Basic Auth capabilities.

See brim.wsgi_basic_auth for more information.

Parameters:
  • name -- The name of the app.
  • parsed_conf -- The conf result from parse_conf().
  • next_app -- The next WSGI app in the chain.
__call__(env, start_response)

Handles incoming requests, adhering to any basic auth settings.

Parameters:
  • env -- The WSGI env as per the spec.
  • start_response -- The WSGI start_response as per the spec.
Returns:

Calls start_response and returns an iterable as per the WSGI spec.

auth_path = None

The auth file path; see brim.wsgi_basic_auth

name = None

The name of the app.

next_app = None

The next WSGI app in the chain.

classmethod parse_conf(name, conf)

Translates the overall server configuration.

The conf is translated into an app-specific configuration dict suitable for passing as parsed_conf in the WSGIBasicAuth constructor.

See the overall docs of brim.wsgi_basic_auth for configuration options.

Parameters:
  • name -- The name of the app, indicates the app's section in the overall configuration for the server.
  • conf -- The brim.conf.Conf instance representing the overall configuration of the server.
Returns:

A dict suitable for passing as parsed_conf in the WSGIBasicAuth constructor.

brim.wsgi_echo

A simple WSGI application that just echoes the request body.

This is a good starting point for other WSGI applications. See the source for what's implemented and why.

Configuration Options:

[wsgi_echo]
call = brim.wsgi_echo.WSGIEcho
# path = <path>
#   The request path to match and serve; any other paths will be
#   passed on to the next WSGI app in the chain. Default: /echo
# max_echo = <bytes>
#   The maximum bytes to echo; any additional bytes will be ignored.
#   Default: 65536

Stats Variables (where n. is the name of the app in the config):

Name Type Description
n.requests sum The number of requests received.
start_time worker Timestamp when the app was started. If the app had to be restarted, this timestamp will be updated with the new start time. This item is available with all apps and set by the controlling brim.server.Subserver.
class brim.wsgi_echo.WSGIEcho(name, parsed_conf, next_app)

Bases: object

A simple WSGI application that just echoes the request body.

This is a good starting point for other WSGI applications. See the source for what's implemented and why.

Parameters:
  • name -- The name of the app.
  • parsed_conf -- The conf result from parse_conf().
  • next_app -- The next WSGI app in the chain.
__call__(env, start_response)

Handles incoming requests.

If the request path exactly matches the one configured for this app, the request body will be read and then sent back in the response. Otherwise, the request is passed on to the next app in the chain.

Parameters:
  • env -- The WSGI env as per the spec.
  • start_response -- The WSGI start_response as per the spec.
Returns:

Calls start_response and returns an iterable as per the WSGI spec.

max_echo = None

The maximum request size to echo back.

name = None

The name of the app.

next_app = None

The next WSGI app in the chain.

classmethod parse_conf(name, conf)

Translates the overall server configuration.

The conf is translated into an app-specific configuration dict suitable for passing as parsed_conf in the WSGIEcho constructor.

See the overall docs of brim.wsgi_echo for configuration options.

Parameters:
  • name -- The name of the app, indicates the app's section in the overall configuration for the server.
  • conf -- The brim.conf.Conf instance representing the overall configuration of the server.
Returns:

A dict suitable for passing as parsed_conf in the WSGIEcho constructor.

path = None

The URL path to serve.

classmethod stats_conf(name, parsed_conf)

Returns a list of (stat_name, stat_type) pairs.

These pairs specify the stat variables this app wants established in the stats instance passed to __call__().

Stats are often retrieved by users and utilities through WSGI apps like brim.wsgi_stats.WSGIStats.

See the overall docs of brim.wsgi_echo for what stats are defined.

The available stat_types are:

worker Indicates a worker only stat. No overall stat will be reported.
sum Indicates an overall stat should be reported that is a sum of the stat from all workers.
min Indicates an overall stat should be reported that is the smallest value of the stat from all workers.
max Indicates an overall stat should be reported that is the largest value of the stat from all workers.
Parameters:
  • name -- The name of the app, indicates the app's section in the overall configuration for the daemon server.
  • parsed_conf -- The result from parse_conf().
Returns:

A list of (stat_name, stat_type) pairs.

brim.wsgi_fs

A WSGI application that simply serves up files from the file system.

Warning

This is an early version of this module. It has no tests, limited documentation, and is subject to major changes.

Configuration Options:

[wsgi_fs]
call = brim.wsgi_fs.WSGIFS
# path = <path>
#   The request path to match and serve; any paths that do not begin
#   with this value will be passed on to the next WSGI app in the
#   chain. Default: /
# serve_path = <path>
#   The local file path containing files to serve.
class brim.wsgi_fs.WSGIFS(name, parsed_conf, next_app)

Bases: object

A WSGI app for serving up files from the file system.

See brim.wsgi_fs for more information.

Parameters:
  • name -- The name of the app.
  • parsed_conf -- The conf result from parse_conf().
  • next_app -- The next WSGI app in the chain.
__call__(env, start_response)

Handles incoming WSGI requests.

Requests that start with the configured path simply serve up any files under the configured location on the file system. Other requests are passed on to the next WSGI app in the chain.

Parameters:
  • env -- The WSGI env as per the spec.
  • start_response -- The WSGI start_response as per the spec.
Returns:

Calls start_response and returns an iterable as per the WSGI spec.

name = None

The name of the app.

next_app = None

The next WSGI app in the chain.

classmethod parse_conf(name, conf)

Translates the overall server configuration.

The conf is translated into an app-specific configuration dict suitable for passing as parsed_conf in the WSGIFS constructor.

See the overall docs of brim.wsgi_fs for configuration options.

Parameters:
  • name -- The name of the app, indicates the app's section in the overall configuration for the server.
  • conf -- The brim.conf.Conf instance representing the overall configuration of the server.
Returns:

A dict suitable for passing as parsed_conf in the WSGIFS constructor.

path = None

The request path to match and serve.

Any paths that do not begin with this value will be passed on to the next WSGI app in the chain. The attribute will have leading and trailing foward slashes removed.

serve_path = None

The local file path containing files to serve.

brim.wsgi_fs.http_date_time(when)

Returns a date and time formatted as per HTTP RFC 2616.

brim.wsgi_stats

Reports the brimd server stats as a JSON reponse.

The stats contain basic things like the server start time and request counts. You may also add a jsonp or callback query variable for JSONP support.

Configuration Options:

[wsgi_stats]
call = brim.wsgi_stats.WSGIStats
# path = <path>
#   The request path to match and serve; any other paths will be
#   passed on to the next WSGI app in the chain. This can serve as a
#   basic restriction to accessing the stats by setting it to a hard
#   to guess value. Default: /stats
class brim.wsgi_stats.WSGIStats(name, parsed_conf, next_app)

Bases: object

Reports the brimd server stats as a JSON response.

See brim.wsgi_stats for more information.

Parameters:
  • name -- The name of the app.
  • parsed_conf -- The conf result from parse_conf().
  • next_app -- The next WSGI app in the chain.
__call__(env, start_response)

Handles incoming WSGI requests.

If the request path exactly matches the one configured for this app, a JSON response will be sent containing the brimd server stats. Otherwise, the request is passed on to the next app in the chain.

Parameters:
  • env -- The WSGI env as per the spec.
  • start_response -- The WSGI start_response as per the spec.
Returns:

Calls start_response and returns an iterable as per the WSGI spec.

name = None

The name of the app.

next_app = None

The next WSGI app in the chain.

classmethod parse_conf(name, conf)

Translates the overall server configuration.

The conf is translated into an app-specific configuration dict suitable for passing as parsed_conf in the WSGIStats constructor.

See the overall docs of brim.wsgi_stats for configuration options.

Parameters:
  • name -- The name of the app, indicates the app's section in the overall configuration for the server.
  • conf -- The brim.conf.Conf instance representing the overall configuration of the server.
Returns:

A dict suitable for passing as parsed_conf in the WSGIStats constructor.

path = None

The request path to exactly match and serve.