Cement Core API Documentation

cement.core.app_setup

Cement methods to setup the framework for applications using it.

cement.core.app_setup.define_default_handler_types()

Defines Cement framework handlers.

Handler Definitions:

output
Output handlers are responsible for rendering output as returned from controller functions. This may be ‘Genshi’, ‘json’, ‘yaml’, ‘Jinja2’, etc.
cement.core.app_setup.define_default_hooks()

Defines Cement framework hooks.

Hook definitions:

options_hook
Used to add options to a namespaces options object
post_options_hook
Run after all options have been setup and merged
validate_config_hook
Run after config options are setup
pre_plugins_hook
Run just before all plugins are loaded (run once)
post_plugins_hook
Run just after all plugins are loaded (run once)
post_bootstrap_hook
Run just after the root bootstrap is loaded.
cement.core.app_setup.lay_cement(config, **kw)

Primary method to setup an application for Cement.

Required Arguments:

config
Dict containing application config.

Optional Keyword Arguments:

banner
Optional text to display for –version
args
Args to use (default: sys.argv)... if passed, args overrides sys.argv because optparse accesses sys.argv.
clear_loggers
Defaults to ‘True’, whether or not to clear existing loggers.

Usage:

from cement.core.configuration import get_default_config
from cement.core.app_setup import lay_cement

lay_cement(get_default_config())
cement.core.app_setup.register_default_handlers()
Register the default base level handlers required to run a Cement application.

cement.core.command

These methods and classes controller how commands are parsed and run.

cement.core.command.run_command(cmd_name=None, ignore_conflicts=False)

Run the command or namespace-subcommand as defined by the ‘expose()’ decorator used on a Controller function.

Keyword arguments:

cmd_name
The command name as store in the global ‘namespaces’. For example, namespaces[‘root’].commands[‘cmd_name’].

cement.core.configuration

Cement methods for handling config file parsing.

cement.core.configuration.ensure_api_compat(module_name, required_api)

Ensure the application is compatible with this version of Cement.

Required Arguments:

module_name
Name of the applications module.
required_api
The Cement API version required by the application.
cement.core.configuration.get_api_version()
Get the Cement API Version.
cement.core.configuration.get_default_config()
Get a default config dict.
cement.core.configuration.get_default_namespace_config()
Get a default plugin config dict.
cement.core.configuration.set_config_opts_per_cli_opts(namespace, cli_opts)

Determine if any config optons were passed via cli options, and if so override the config option. Overwrites the global namespaces[‘namespace’].config dict.

Required arguments:

namespace
The namespace of whose config to modify.
cli_opts
The cli_opts as parsed from OptParse.
cement.core.configuration.set_config_opts_per_file(namespace, section, config_file)

Parse config file options for into config dict. Will do nothing if the config file does not exist.

Required arguments:

namespace
The namespace to set config options for
section
Section of the configuration file to read.
config_file
The config file to parse.
cement.core.configuration.t_f_pass(value)

A quick hack for making true/false type values actually True/False in python.

Required arguments:

value
The presumed ‘true’ or ‘false’ value.

Returns:

boolean
True/False based on logic of the operation.
cement.core.configuration.validate_config(config)

Validate that all required cement configuration options are set. Also creates any common directories based on config settings if they do not exist.

Required arguments:

config
The config dict to validate.

Possible Exceptions:

CementConfigError
Raised on invalid configuration.

cement.core.controller

Methods and classes to handle Cement Controller functions.

class cement.core.controller.CementController(cli_opts=None, cli_args=None)
Currently just a place holder for more featureful controller.
cement.core.controller.expose

Decorator function for plugins to expose commands. Used as:

Arguments:

template
A template in python module form (i.e ‘myapp.templates.mytemplate’)
namespace
The namespace to expose the command in. Default: root

Optional Keyword Arguments:

is_hidden
True/False whether command should display on –help.

Usage:

class MyController(CementController):
    @expose('myapp.templates.mycontroller.cmd', namespace='root')
    def cmd(self):
        foo="Foo"
        bar="Bar"
        return dict(foo=foo, bar=bar)
cement.core.controller.run_controller_command(namespace, func, cli_opts=None, cli_args=None, *args, **kw)

Cleanly run a command function from a controller. Returns a tuple of (result_dict, output_txt).

Arguments:

namespace
The namespace of the controller
func
The name of the function
cli_opts
Options passed to the command line
cli_args
Arguments passed to the command line
args
Any additional arguments to pass to the function
kwargs
Any additional keyword arguments to pass to the function.

Usage:

from cement.core.controller import run_controller_command

run_controller_command('root', 'cmd_name', myarg=True)

cement.core.exc

Cement exception classes.

exception cement.core.exc.CementArgumentError(value)
Argument errors.
exception cement.core.exc.CementConfigError(value)
Config parsing and setup errors.
exception cement.core.exc.CementError(value, code=1)
Generic errors.
exception cement.core.exc.CementRuntimeError(value)
Runtime errors.

cement.core.hook

Methods and classes to handle Cement Hook support.

cement.core.hook.define_hook(name)

Define a hook namespace that plugins can register hooks in.

Required arguments:

name
The name of the hook, stored as hooks[‘name’]

Usage:

from cement.core.hook import define_hook

define_hook('myhookname_hook')
class cement.core.hook.register_hook(weight=0, name=None)

Decorator function for plugins to register hooks. Used as:

Optional keyword arguments:

weight
The weight in which to order the hook function (default: 0)
name
The name of the hook to register too. If not passed, the __name__ of the decorated function will be used.

Usage:

from cement.core.hook import register_hook

@register_hook()
def my_hook(*args, **kwargs):
    # do something here
    res = 'Something to return'
    return res
cement.core.hook.run_hooks(name, *args, **kwargs)

Run all defined hooks in the namespace. Yields the result of each hook function run.

Optional arguments:

name
The name of the hook function
args
Any additional args are passed to the hook function
kwargs
Any kwargs are passed to the hook function

Usage:

from cement.core.hook import run_hook

for result in run_hooks('hook_name'):
    # do something with result from each hook function
    ...

cement.core.log

Cement methods to setup and configuring logging.

cement.core.log.clear_previous_loggers()
Clear all previous loggers that have been setup (by this, or other applications).
cement.core.log.get_logger(name)

Used throughout the application to get a logger opject with a namespace of ‘name’ (should be passed as __name__).

Arguments:

name
Name of the module calling get_logger (use __name__).

Usage:

from cement.core.log import get_logger
log = get_logger(__name__)
cement.core.log.setup_default_logging(level, to_console)

Default logging config.

Required Arguments:

level
The log level to use ([‘INFO’, ‘WARN’, ‘ERROR’, ‘DEBUG’, ‘FATAL’])
to_console
Whether to setup console logging or not.
cement.core.log.setup_logging(clear_loggers=True, level=None, to_console=True)

Primary Cement method to setup logging.

Keyword arguments:

clear_loggers
Boolean, whether to clean exiting loggers (default: True)
level
The log level (info, warn, error, debug, fatal), (default: None)
to_console
Boolean, whether or not to log to console

Usage:

from cement.core.log import setup_logging
setup_logging()
cement.core.log.setup_logging_for_plugin_provider(provider)

Setup the logging handlers for a plugin providers module name space.

Required Arguments:

provider
The name of the application (module) providing the shared plugin.
cement.core.log.setup_logging_per_config(config_file_path)
Setup logging using a logging fileCondfig. See: http://docs.python.org/library/logging.html#logging.fileConfig

cement.core.namespace

Methods and classes to handle Cement namespace support.

class cement.core.namespace.CementNamespace(label, **kw)

Class that handles plugins and namespaces.

Required Arguments:

label
Namespace label. Class is stored in the global ‘namespaces’ dict as namespaces[‘label’].
version
The version of the application.

Optional Keyword Arguments:

description
Description of the plugin/namespace (default: ‘’)
commands
A dict of command functions (default: {})
is_hidden
Boolean, whether command should display in –help output (default: False)
config
A configobj object (default: None). A basic default config will be created if none is passed. For advanced configurations such as using a configspec or what have you can be done by passing in the configobj object.
banner
A version banner to display for –version (default: ‘’)
required_api
The required Cement API the application was built on. (Deprecated as of 0.8.9)
cement.core.namespace.define_namespace(namespace, namespace_obj)

Define a namespace for commands, options, configuration, etc.

Required Arguments:

namespace
Label of the namespace
namespace_obj
CementNamespace object. Stored in global ‘namespaces’ dict as namespaces[‘namespace’]
cement.core.namespace.get_config(namespace='root')

Get a namespace’s config. Returns a ConfigObj object.

Optional Arguments:

namespace
The namespace to pull the config object from. Default: ‘root’.
cement.core.namespace.get_namespace(namespace)

Return the namespace object whose label is ‘namespace’.

Required Arguments:

namespace
The label of the namespace object to return
cement.core.namespace.register_namespace(namespace_obj)

Wraps up defining a namespace, as well as revealing the actual controller object (as it is passed as a string).

Require Arguments:

namespace_obj
Namespace object that is fully established (and ready to be added to the global namespaces dictionary)

Usage:

from cement.core.namespace import CementNamespace, register_namespace

example = CementNamespace('example', controller='ExampleController')
example.config['foo'] = 'bar'
example.options.add_option('-F', '--foo', action='store',
    dest='foo', default=None, help='Example Foo Option')
register_namespace(example)

cement.core.opt

Cement methods and classes to handle cli option/arg parsing.

cement.core.opt.init_parser(banner=None)

Create an OptionParser object and returns its parser member.

Keyword arguments:

banner
Optional version banner to display for –version

Returns: OptionParser object.

cement.core.opt.parse_options(namespace='root', ignore_conflicts=False)

The actual method that parses the command line options and args. Also handles all the magic that happens when you pass –help to your app. It also handles merging root options into plugins, if the plugins config is set to do so (merge_root_options)

Required Arguments:

namespace
The namespace to parse options for (defaullt: ‘root’)

Returns: tuple (options, args)

cement.core.plugin

Methods and classes to handle Cement plugin support.

cement.core.plugin.get_enabled_plugins()
Open plugin config files from plugin_config_dir and determine if they are enabled. If so, append them to ‘enabled_plugins’ in the root config. Uses the namespaces[‘root’].config dictionary.
cement.core.plugin.load_all_plugins()
Attempt to load all enabled plugins. Passes the existing config and options object to each plugin and allows them to add/update each.
cement.core.plugin.load_plugin(plugin)

Load a cement plugin.

Required arguments:

plugin
Name of the plugin to load. Should be accessible from the module path of ‘myapp.plugin.myplugin’.

cement.core.view

Methods and classes that enable Cement templating support.

class cement.core.view.CementOutputHandler(data, template=None)

This is the standard class for output handling. All output handlers should subclass from here.

Required Arguments:

data
The dictionary returned from a controller function.
template
The template file in module form, such as: (myapp.templates.namespace.file) where the path to the file is actually myapp/templates/namespace/file.txt or similar.
render()
Using the contents of the template file, or from the data dictionary directly, render output. Will raise NotImplementedError if not subclassed.
class cement.core.view.JsonOutputHandler(data, template=None)

Render output into JSON from the controller data dictionary. The template param is ignored.

Required Arguments:

data
The dictionary returned from a controller function.
template
Ignored by this handler

Usage:

from cement.core.handler import get_handler

fake_dict = dict(foo='String', bar=100, list=[1,2,3,4,5])
handler = get_handler('output', 'json')(fake_dict)
output = handler.render()
class cement.core.view.render(output_handler, template=None)

Class decorator to render data with the specified output handler. Called when the function is decorated, sets up the engine and template for later use.

Note: This is called from the cement.core.controller.expose() decorator and likely shouldn’t ever be needed to call directly.

Note: If ‘output_file’ is passed in the return dictionary from func, then the output is written to the specified file rather than STDOUT.

Keywork arguments:

output_handler
The name of the output handler to use for rendering
template
The module path to the template (default: None)

When called, a tuple is returned consisting of (dict, output), meaning the first item is the result dictionary as returned by the original function, and the second is the output as rendered by the output handler.