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. |
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
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: |
|
|---|
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: |
|
|---|
A list of source conf file names the conf was read from.
Returns the value of the section/option.
Returns the boolean value of the section/option.
Returns the float value of the section/option.
Returns the int value of the section/option.
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.
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.
A list of lowercase string values that equate to False.
A list of lowercase string values that equate to 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: |
|
|---|---|
| Returns: | A new Conf instance representing the configuration read from the conf_files. |
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. |
Bases: object
A simple daemon that just logs a status line every so often.
| Parameters: |
|
|---|
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: |
|
|---|---|
| Returns: | Hopefully never. If the method does return, the caller should create a new daemon instance and call this method again. |
The number of seconds between each status line logged.
The name of the daemon.
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: |
|
|---|---|
| Returns: | A dict suitable for passing as parsed_conf in the DaemonSample constructor. |
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: |
|
|---|---|
| Returns: | A list of (stat_name, stat_type) pairs. |
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).
Translates an HTTP status code to an English reason string.
Bases: brim.http.HTTPSuccess
Bases: brim.http.HTTPSuccess
Bases: brim.http.HTTPServerError
alias of HTTPClientError
Bases: brim.http.HTTPError
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPInformational
Bases: brim.http.HTTPSuccess
Bases: brim.http.HTTPException
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: |
|
|---|
WSGI callable.
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPRedirection
Bases: brim.http.HTTPServerError
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPServerError
Bases: brim.http.HTTPSuccess
Bases: brim.http.HTTPException
Bases: brim.http.HTTPServerError
alias of HTTPServerError
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPServerError
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPRedirection
Bases: brim.http.HTTPSuccess
alias of HTTPRedirection
Bases: brim.http.HTTPSuccess
Bases: brim.http.HTTPSuccess
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPServerError
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPServerError
Bases: brim.http.HTTPRedirection
alias of HTTPSuccess
alias of HTTPSuccess
Bases: brim.http.HTTPSuccess
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPInformational
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPException
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPSuccess
alias of HTTPException
Bases: brim.http.HTTPRedirection
Bases: brim.http.HTTPError
Bases: brim.http.HTTPServerError
Bases: brim.http.HTTPException
Bases: brim.http.HTTPInformational
Bases: brim.http.HTTPRedirection
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPClientError
Bases: brim.http.HTTPRedirection
Bases: brim.http.HTTPServerError
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. |
|---|
Returns the value of the query parameter.
| Parameters: |
|
|---|
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: |
|
|---|
Returns the float value of the query parameter.
If the value cannot be translated to a float, raises HTTPBadRequest.
| Parameters: |
|
|---|
Returns the int value of the query parameter.
If the value cannot be translated to an int, raises HTTPBadRequest.
| Parameters: |
|
|---|
Returns the value of an HTTP header.
| Parameters: |
|
|---|
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: |
|
|---|
Returns the float value of an HTTP header.
If the value cannot be translated to a float, raises HTTPBadRequest.
| Parameters: |
|
|---|
Returns the int value of an HTTP header.
If the value cannot be translated to an int, raises HTTPBadRequest.
| Parameters: |
|
|---|
Patched version of urllib.quote that UTF8 encodes unicode.
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.
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')
Bases: exceptions.Exception
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: |
|
|---|---|
| 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. |
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'))
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.
Returns a Logger based on the information given.
| Parameters: |
|
|---|
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.
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. |
|---|
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.
The list of default conf files to use when none are specified.
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. |
|---|
The status code for requests terminated early by the client (499).
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: |
|
|---|
The seconds to wait for a PID to disappear after signaling.
Bases: object
The main entry point for the Brim.Net Core Server, brimd.
Few daemons or apps need to access this directly.
| Parameters: |
|
|---|
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. |
|---|
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: |
|
|---|
The json.dumps compatible function configured.
WSGI apps can also access this via env['brim.json_dumps'].
The json.loads compatible function configured.
WSGI apps can also access this via env['brim.json_loads'].
The logger in use by this subserver.
WSGI apps can also access this via env['brim.logger'].
The parent brim.server.Server of this subserver.
Bases: brim.server.IPSubserver
Subserver for TCP.
Created for each [tcp], [tcp2], [tcp3] config section to hold the attributes specific to that subconfig.
| Parameters: |
|
|---|
Bases: brim.server.IPSubserver
Subserver for UDP.
Created for each [udp], [udp2], [udp3] config section to hold the attributes specific to that subconfig.
| Parameters: |
|
|---|
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: |
|
|---|
Default WSGI application that responds with 404 Not Found.
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. |
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: |
|
|---|---|
| Returns: | The response as (status_line, headers_iteritems, excinfo, content_iter). |
brimd script entry point.
Provides functions useful for background services.
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).
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: |
|
|---|
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: |
|
|---|
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: |
|
|---|
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. |
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: |
|
|---|
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. |
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: |
|
|---|
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: |
|
|---|
The most to read from the client at once.
The name of the app.
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: |
|
|---|---|
| Returns: | A dict suitable for passing as parsed_conf in the TCPEcho constructor. |
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: |
|
|---|---|
| Returns: | A list of (stat_name, stat_type) pairs. |
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. |
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: |
|
|---|
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: |
|
|---|
The name of the app.
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: |
|
|---|---|
| Returns: | A dict suitable for passing as parsed_conf in the UDPEcho constructor. |
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: |
|
|---|---|
| Returns: | A list of (stat_name, stat_type) pairs. |
Miscellaneous classes and functions.
Bases: exceptions.Exception
Raised by lock_path() if its timeout is reached.
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: |
|
|---|
os.makedirs but ignoring errors due to the path already existing.
| Parameters: |
|
|---|
os.unlink but ignoring errors due to the path already not existing.
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.
Bases: object
A WSGI application that offers Basic Auth capabilities.
See brim.wsgi_basic_auth for more information.
| Parameters: |
|
|---|
Handles incoming requests, adhering to any basic auth settings.
| Parameters: |
|
|---|---|
| Returns: | Calls start_response and returns an iterable as per the WSGI spec. |
The auth file path; see brim.wsgi_basic_auth
The name of the app.
The next WSGI app in the chain.
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: |
|
|---|---|
| Returns: | A dict suitable for passing as parsed_conf in the WSGIBasicAuth constructor. |
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. |
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: |
|
|---|
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: |
|
|---|---|
| Returns: | Calls start_response and returns an iterable as per the WSGI spec. |
The maximum request size to echo back.
The name of the app.
The next WSGI app in the chain.
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: |
|
|---|---|
| Returns: | A dict suitable for passing as parsed_conf in the WSGIEcho constructor. |
The URL path to serve.
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: |
|
|---|---|
| Returns: | A list of (stat_name, stat_type) pairs. |
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.
Bases: object
A WSGI app for serving up files from the file system.
See brim.wsgi_fs for more information.
| Parameters: |
|
|---|
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: |
|
|---|---|
| Returns: | Calls start_response and returns an iterable as per the WSGI spec. |
The name of the app.
The next WSGI app in the chain.
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: |
|
|---|---|
| Returns: | A dict suitable for passing as parsed_conf in the WSGIFS constructor. |
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.
The local file path containing files to serve.
Returns a date and time formatted as per HTTP RFC 2616.
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
Bases: object
Reports the brimd server stats as a JSON response.
See brim.wsgi_stats for more information.
| Parameters: |
|
|---|
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: |
|
|---|---|
| Returns: | Calls start_response and returns an iterable as per the WSGI spec. |
The name of the app.
The next WSGI app in the chain.
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: |
|
|---|---|
| Returns: | A dict suitable for passing as parsed_conf in the WSGIStats constructor. |
The request path to exactly match and serve.