Cement2 Core Modules

cement2.core.arg

Cement core argument module.

class cement2.core.arg.CementArgumentHandler(*args, **kw)

Base class that all Argument Handlers should sub-class from.

class cement2.core.arg.IArgument

This class defines the Argument Handler Interface. Classes that implement this handler must provide the methods and attributes defined below. Implementations do not subclass from interfaces.

Example:

from cement2.core import interface, arg

class MyArgumentHandler(arg.CementArgumentHandler):
    class Meta:
        interface = arg.IArgument
        label = 'my_argument_handler'
add_argument(*args, **kw)

Add arguments for parsing. This should be -o/–option or positional.

Positional Arguments:

args
List of option arguments. Generally something like [‘-h’, ‘–help’].

Optional Arguments

dest
The destination name (var). Default: arg[0]’s string.
help
The help text for –help output (for that argument).
action
Must support: [‘store’, ‘store_true’, ‘store_false’, ‘store_const’]
const
The value stored if action == ‘store_const’.
default
The default value.

Return: None

parse(arg_list)

Parse the argument list (i.e. sys.argv). Can return any object as long as it’s members contain those of the added arguments. For example, if adding a ‘-v/–version’ option that stores to the dest of ‘version’, then the member must be callable as ‘Object().version’.

Must also set self.parsed_args to what is being returned.

Required Arguments:

arg_list
A list of command line arguments.

Return: Callable

cement2.core.arg.argument_validator(klass, obj)

Validates a handler implementation against the IArgument interface.

cement2.core.backend

Cement core backend module.

cement2.core.backend.defaults(*sections)

Returns a standard dictionary object to use for application defaults. If sections are given, it will create a nested dict for each section name.

Usage:

from cement2.core import foundation, backend

defaults = backend.defaults(‘myapp’, ‘section2’, ‘section3’) defaults[‘myapp’][‘debug’] = False defaults[‘section2’][‘foo’] = ‘bar defaults[‘section3’][‘foo2’] = ‘bar2’

app = foundation.CementApp(‘myapp’, config_defaults=defaults)

cement2.core.backend.minimal_logger(name, debug=False)

Setup just enough for cement to be able to do debug logging. This is the logger used by the Cement framework, which is setup and accessed before the application is functional (and more importantly before the applications log handler is usable).

Required Arguments:

name
The logging namespace. This is generally ‘__name__’ or anything you want.

Optional Arguments:

debug

Toggle debug output.

Default: False

Usage:

from cement2.core import backend
Log = backend.minimal_logger('cement')
Log.debug('This is a debug message')

cement2.core.config

Cement core config module.

class cement2.core.config.CementConfigHandler(*args, **kw)

Base class that all Config Handlers should sub-class from.

class cement2.core.config.IConfig

This class defines the Config Handler Interface. Classes that implement this handler must provide the methods and attributes defined below.

All implementations must provide sane ‘default’ functionality when instantiated with no arguments. Meaning, it can and should accept optional parameters that alter how it functions, but can not require any parameters. When the framework first initializes handlers it does not pass anything too them, though a handler can be instantiated first (with or without parameters) and then passed to ‘CementApp()’ already instantiated.

Implementations do not subclass from interfaces.

Usage:

from cement2.core import config

class MyConfigHandler(config.CementConfigHandler):
    class Meta:
        interface = config.IConfig
        label = 'my_config_handler'
    ...
add_section(section)

Add a new section if it doesn’t exist.

Required Arguments:

section
The [section] label to create.

Return: None

get(section, key)

Return a configuration value based on [section][key]. The return value type is unknown.

Required Arguments:

section
The [section] of the configuration to pull key value from.
key
The configuration key to get the value from.

Return: unknown

get_section_dict(section)

Return a dict of configuration parameters for [section].

Required Arguments:

section
The config [section] to generate a dict from (using that sections keys).

Return: dict

get_sections()

Return a list of configuration sections. These are designated by a [block] label in a config file.

Return: list

has_section(section)

Returns whether or not the section exists.

Return: bool

keys(section)

Return a list of configuration keys from section.

Required Arguments:

section
The config [section] to pull keys from.

Return: list

merge(dict_obj, override=True)

Merges a dict object into the configuration.

Required Arguments:

dict_obj
The dict to merge into the config

Optional Arguments:

override
Whether to override existing values. Default: True

Return: None

parse_file(file_path)

Parse config file settings from file_path. Returns True if the file existed, and was parsed successfully. Returns False otherwise.

Required Arguments:

file_path
The path to the config file to parse.

Return: boolean

set(section, key, value)

Set a configuration value based at [section][key].

Required Arguments:

section
The [section] of the configuration to pull key value from.
key
The configuration key to set the value at.
value
The value to set.

Return: None

cement2.core.config.config_validator(klass, obj)

Validates a handler implementation against the IConfig interface.

cement2.core.controller

Cement core controller module.

class cement2.core.controller.CementBaseController(*args, **kw)

This is an implementation of the IControllerHandler interface, but as a base class that application controllers need to subclass from. Registering it directly as a handler is useless.

NOTE: This handler requires that the applications ‘arg_handler’ be argparse. If using an alternative argument handler you will need to write your own controller base class.

Optional / Meta Options:

interface
The interface that this controller implements (IController).
label
The label of the controller. Will be used as the sub-command name for ‘stacked’ controllers.
description
The description shown at the top of ‘–help’.
config_section

A config [section] to merge config_defaults into.

Default: controller.<label>

config_defaults
Configuration defaults (type: dict) that are merged into the applications config object.
arguments

Arguments to pass to the argument_handler. The format is a list of tuples whos items are a ( list, dict ). Meaning:

[ ( [‘-f’, ‘–foo’], dict(dest=’foo’, help=’foo option’) ), ]
stacked_on
A label of another controller to ‘stack’ commands/arguments on top of.
hide
Whether or not to hide the controller entirely.
epilog
The text that is displayed at the bottom when ‘–help’ is passed.

Usage:

from cement2.core import controller
   
class MyAppBaseController(controller.CementBaseController):
    class Meta:
        interface = controller.IController
        label = 'base'
        description = 'MyApp is awesome'
        config_defaults = dict()
        arguments = []
        epilog = "This is the text at the bottom of --help."
    ...
default()

This is the default action if no arguments (sub-commands) are passed at command line.

class cement2.core.controller.IController

This class defines the Controller Handler Interface. Classes that implement this handler must provide the methods and attributes defined below.

Implementations do not subclass from interfaces.

Usage:

from cement2.core import controller

class MyBaseController(controller.CementBaseController):
    class Meta:
        interface = controller.IController
        label = 'my_base_controller'
        description = 'My applications base controller'
        epilog = 'Example: myapp.py --foo=bar'
        hide = False
        config_section = 'base'
        config_defaults = dict(
            foo='bar',
            )
        arguments = [
            ( ['-f', '--foo'], dict(help='Foo option', dest='foo') ),
            ]
cement2.core.controller.controller_validator(klass, obj)

Validates a handler implementation against the IController interface.

class cement2.core.controller.expose(hide=False, help='', aliases=[])

Used to expose controller functions to be listed as commands, and to decorate the function with Meta data for the argument parser.

Optional Arguments:

hide
Whether the command should be visible.
help
Help text to display for that command.
aliases
List of aliases to this command.

Usage:

from cement2.core import controller

class MyAppBaseController(controller.CementBaseController):
    class Meta:
        interface = controller.IController
        label = 'base'
        
    @controller.expose(hide=True, aliases=['run'])
    def default(self):
        print("In MyAppBaseController.default()")

    @controller.expose()
    def my_command(self):
        print("In MyAppBaseController.my_command()")

cement2.core.exc

Cement core exceptions module.

exception cement2.core.exc.CementError(msg)

Generic errors.

exception cement2.core.exc.CementSignalError(signum, frame)

Signal errors.

cement2.core.extension

Cement core extensions module.

class cement2.core.extension.IExtension

This class defines the Extension Handler Interface. Classes that implement this handler must provide the methods and attributes defined below.

Implementations do not subclass from interfaces.

Usage:

from cement2.core import extension

class MyExtensionHandler(object):
    class Meta:
        interface = extension.IExtension
        label = 'my_extension_handler'
    ...
load_extension(ext_module)

Load an extension whose module is ‘ext_module’. For example, ‘cement2.ext.ext_configobj’.

Required Arguments:

ext_module
The name of the extension to load.
load_extensions(ext_list)

Load all extensions from ext_list.

Required Arguments:

ext_list
A list of extension modules to load. For example, [‘cement2.ext.ext_configobj’, ‘cement2.ext.ext_logging’].
cement2.core.extension.extension_validator(klass, obj)

Validates an handler implementation against the IExtension interface.

cement2.core.foundation

Cement core application module.

class cement2.core.foundation.CementApp(label=None, **kw)

The primary class to build applications from.

Optional / Meta Arguments:

label

The name of the application. This should be the common name as you would see and use at the command line. For example ‘helloworld’, or ‘my-awesome-app’.

Default: None

debug

Toggles debug output. By default, this setting is also overridden by the ‘[base] -> debug’ config setting parsed in any of the application configuration files (where [base] is the base configuration section of the application which is determined by Meta.config_section but defaults to Meta.label).

Default: False

argv

A list of arguments to use for parsing command line arguments and options.

Default: sys.argv

config_section

The base configuration section for the application.

Default: None

Note: Though Meta.config_section defaults to None, Cement will set this to the value of Meta.label (or in other words, the name of the application).

config_defaults

Default configuration dictionary. Must be of type ‘dict’.

Default: None

config_files

List of config files to parse.

Default: None

plugins

A list of plugins to load. This is generally considered bad practice since plugins should be dynamically enabled/disabled via a plugin config file.

Default: []

plugin_config_dir

A directory path where plugin config files can be found. Files must end in ‘.conf’. By default, this setting is also overridden by the ‘[base] -> plugin_config_dir’ config setting parsed in any of the application configuration files.

Default: None

Note: Though the meta default is None, Cement will set this to ‘/etc/<app_label>/plugins.d/’ if not set during app.setup().

plugin_dir

A directory path where plugin code (modules) can be loaded from. By default, this setting is also overridden by the ‘[base] -> plugin_dir’ config setting parsed in any of the application configuration files (where [base] is the base configuration section of the application which is determined by Meta.config_section but defaults to Meta.label).

Default: None

Note: Though the meta default is None, Cement will set this to ‘/usr/lib/<app_label>/plugins/’ if not set during app.setup()

plugin_bootstrap

A python package (dotted import path) where plugin code can be loaded from. This is generally something like ‘myapp.bootstrap’.

Default: None

catch_signals

List of signals to catch, and raise exc.CementSignalError for. Can be set to None to disable signal handling.

Default: [
signal.SIGTERM, signal.SIGINT ].
signal_handler

A function that is called to handle any caught signals.

Default: cement2.core.foundation.cement_signal_handler

config_handler

A handler class that implements the IConfig interface. This can be a string (label of a registered handler), an uninstantiated class, or an instantiated class object.

Default: cement2.lib.ext_configparser.ConfigParserConfigHandler

extension_handler

A handler class that implements the IExtension interface. This can be a string (label of a registered handler), an uninstantiated class, or an instantiated class object.

Default: cement2.core.extension.CementExtensionHandler

log_handler

A handler class that implements the ILog interface. This can be a string (label of a registered handler), an uninstantiated class, or an instantiated class object.

Default: cement2.lib.ext_logging.LoggingLogHandler

plugin_handler

A handler class that implements the IPlugin interface. This can be a string (label of a registered handler), an uninstantiated class, or an instantiated class object.

Default: cement2.lib.ext_plugin.CementPluginHandler

argument_handler

A handler class that implements the IArgument interface. This can be a string (label of a registered handler), an uninstantiated class, or an instantiated class object.

Default: cement2.lib.ext_argparse.ArgParseArgumentHandler

output_handler

A handler class that implements the IOutput interface. This can be a string (label of a registered handler), an uninstantiated class, or an instantiated class object.

Default: cement2.lib.ext_nulloutput.NullOutputHandler

cache_handler

A handler class that implements the ICache interface. This can be a string (label of a registered handler), an uninstantiated class, or an instantiated class object.

Default: None

base_controller

This is the base application controller. If a controller is set, runtime operations are passed to the controller for command dispatch and argument parsing when CementApp.run() is called.

Default: None

core_extensions

List of Cement core extensions. These are generally required by Cement and should only be modified if you know what you’re doing. Use ‘extensions’ to add to this list, rather than overriding core extensions. That said if you want to prune down your application, you can remove core extensions if they are not necessary (for example if using your own log handler extension you likely don’t want/need LoggingLogHandler to be registered).

Default: [
‘cement2.ext.ext_nulloutput’, ‘cement2.ext.ext_plugin’, ‘cement2.ext.ext_configparser’, ‘cement2.ext.ext_logging’, ‘cement2.ext.ext_argparse’, ]
extensions

List of additional framework extensions to load.

Default: []

core_meta_override

List of meta options that can/will be overridden by config options of the ‘[base]’ config section (where [base] is the base configuration section of the application which is determined by Meta.config_section but defaults to Meta.label). These overrides are required by the framework to function properly and should not be used by end user (developers) unless you really know what you’re doing. To add your own extended meta overrides please use ‘meta_override’.

Default: [
‘debug’, ‘plugin_config_dir’, ‘plugin_dir’ ]
meta_override

List of meta options that can/will be overridden by config options of the ‘[base]’ config section (where [base] is the base configuration section of the application which is determined by Meta.config_section but defaults to Meta.label).

Default: []

Usage:

The following is the simplest CementApp:

from cement2.core import foundation
try:
    app = foundation.CementApp('helloworld')
    app.setup()
    app.run()
finally:
    app.close()

A more advanced example looks like:

from cement2.core import foundation, controller

class MyController(controller.CementBaseController):
    class Meta:
        label = 'base'
        arguments = [
            ( ['-f', '--foo'], dict(help='Notorious foo option') ),
            ]
        config_defaults = dict(
            debug=False,
            some_config_param='some_value',
            )
    
    @controller.expose(help='This is the default command', hide=True)
    def default(self):
        print('Hello World')
            
class MyApp(foundation.CementApp):
    class Meta:
        label = 'helloworld'
        extensions = [
            'daemon',
            'json',
            ]
        base_controller = MyController

try:
    app = MyApp()
    app.setup()
    app.run()
finally:
    app.close()
add_arg(*args, **kw)

A shortcut for self.args.add_argument.

close()

Close the application. This runs the cement_on_close_hook() allowing plugins/extensions/etc to ‘cleanup’ at the end of program execution.

extend(member_name, member_object)

Extend the CementApp() object with additional functions/classes such as ‘app.my_custom_function()’, etc. It provides an interface for extensions to provide functionality that travel along with the application object.

Required Arguments:

member_name
The name to attach the object to.
member_object
The function or class object to attach to CementApp().
pargs

A shortcut for self.args.parsed_args.

render(data, template=None)

This is a simple wrapper around self.output.render() which simply returns an empty string if no self.output handler is defined.

Required Arguments:

data
The data dictionary to render.

Optional Arguments:

template
The template to render to. Default: None (some output handlers do not use templates).
run()

This function wraps everything together (after self._setup() is called) to run the application.

setup()

This function wraps all ‘_setup’ actons in one call. It is called before self.run(), allowing the application to be _setup but not executed (possibly letting the developer perform other actions before full execution.).

All handlers should be instantiated and callable after _setup() is complete.

validate_config()

Validate application config settings.

cement2.core.foundation.cement_signal_handler(signum, frame)

Catch a signal, run the cement_signal_hook, and then raise an exception allowing the app to handle logic elsewhere.

cement2.core.foundation.lay_cement(name, klass=<class 'cement2.core.foundation.CementApp'>, *args, **kw)

This function is deprecated. Please use CementApp() directly.

cement2.core.handler

Cement core handler module.

class cement2.core.handler.CementBaseHandler(**kw)

All handlers should subclass from here.

Optional / Meta Options:

label
The identifier of this handler
interface
The interface that this handler implements.
config_section

A config [section] to merge config_defaults with.

Default: <interface_label>.<handler_label>

config_defaults
A config dictionary that is merged into the applications config in the [<config_section>] block. These are defaults and do not override any existing defaults under that section.
cement2.core.handler.define(interface)

Define a handler based on the provided interface. Defines a handler type based on <interface>.IMeta.label.

Required arguments:

interface
The handler interface class that defines the interface to be implemented.

Usage:

from cement2.core import handler

handler.define(IDatabaseHandler)
cement2.core.handler.defined(handler_type)

Test whether a handler type is defined.

Required Arguments:

handler_type
The name or ‘type’ of the handler (I.e. ‘logging’).

Returns: bool

cement2.core.handler.enabled(handler_type, handler_label)

Deprecated as of 1.9.5. Use handler.registered().

cement2.core.handler.get(handler_type, handler_label, *args)

Get a handler object.

Required Arguments:

handler_type
The type of handler (i.e. ‘output’)
handler_label
The label of the handler (i.e. ‘json’)

Optional Arguments:

fallback
A fallback value to return if handler_label doesn’t exist.

Usage:

from cement2.core import handler output = handler.get(‘output’, ‘json’) output.render(dict(foo=’bar’))
cement2.core.handler.list(handler_type)

Return a list of handlers for a given type.

Required Arguments:

handler_type
The type of handler (i.e. ‘output’)
cement2.core.handler.register(obj)

Register a handler object to a handler. If the same object is already registered then no exception is raised, however if a different object attempts to be registered to the same name a CementRuntimeError is raised.

Required Options:

obj
The handler object to register

Usage:

from cement2.core import handler

class MyDatabaseHandler(object):
    class Meta:
        interface = IDatabase
        label = 'mysql'
    
    def connect(self):
    ...
    
handler.register(MyDatabaseHandler)
cement2.core.handler.registered(handler_type, handler_label)

Check if a handler is registered.

Required Arguments:

handler_type
The type of handler
handler_label
The label of the handler

Returns: Boolean

cement2.core.hook

Cement core hooks module.

cement2.core.hook.define(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 import hook

hook.define('myhookname_hook')
cement2.core.hook.defined(hook_name)

Test whether a hook name is defined.

Required Arguments:

hook_type
The name of the hook (I.e. ‘my_hook_does_awesome_things’).

Returns: bool

class cement2.core.hook.register(weight=0, name=None)

Decorator function for plugins to register hooks.

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 import hook

@hook.register()
def my_hook(*args, **kwargs):
    # do something here
    res = 'Something to return'
    return res
cement2.core.hook.run(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 import hook

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

cement2.core.interface

Cement core interface module.

cement2.core.interface.validate(interface, obj, members=[], meta=['interface', 'label'])

A wrapper to validate interfaces.

Required Arguments:

interface
The interface class to validate against
obj
The object to validate.

Optional Arguments:

members
The object members that must exist.
meta
The meta object members that must exist.

cement2.core.log

Cement core log module.

class cement2.core.log.CementLogHandler(*args, **kw)

Base class that all Log Handlers should sub-class from.

class cement2.core.log.ILog

This class defines the Log Handler Interface. Classes that implement this handler must provide the methods and attributes defined below.

Implementations do not subclass from interfaces.

Usage:

from cement2.core import log

class MyLogHandler(object):
    class Meta:
        interface = log.ILog
        label = 'my_log_handler'
    ...
clear_loggers()

Clear all existing loggers.

debug(msg)

Log to the ‘DEBUG’ facility.

Required Arguments:

msg
The message to log.
error(msg)

Log to the ‘ERROR’ facility.

Required Arguments:

msg
The message to log.
fatal(msg)

Log to the ‘FATAL’ facility.

Required Arguments:

msg
The message to log.
info(msg)

Log to the ‘INFO’ facility.

Required Arguments:

msg
The message to log.
level()

Return a string representation of the log level.

set_level()

Set the log level. Must except one of: ‘INFO’, ‘WARN’, ‘ERROR’, ‘DEBUG’, or ‘FATAL’.

warn(msg)

Log to the ‘WARN’ facility.

Required Arguments:

msg
The message to log.
cement2.core.log.log_validator(klass, obj)

Validates an handler implementation against the ILog interface.

cement2.core.output

Cement core output module.

class cement2.core.output.CementOutputHandler(*args, **kw)

Base class that all Output Handlers should sub-class from.

class cement2.core.output.IOutput

This class defines the Output Handler Interface. Classes that implement this handler must provide the methods and attributes defined below.

Implementations do not subclass from interfaces.

Usage:

from cement2.core import output

class MyOutputHandler(object):
    class Meta:
        interface = output.IOutput
        label = 'my_output_handler'
    ...
render(data_dict, template=None)

Render the data_dict into output in some fashion.

Required Arguments:

data_dict
The dictionary whose data we need to render into output.

Optional Paramaters:

template
A template to use for rendering (in module form). I.e. myapp.templates.some_command

Returns: string or unicode string or None

cement2.core.output.output_validator(klass, obj)

Validates an handler implementation against the IOutput interface.

cement2.core.plugin

Cement core plugins module.

class cement2.core.plugin.CementPluginHandler(*args, **kw)

Base class that all Plugin Handlers should sub-class from.

class cement2.core.plugin.IPlugin

This class defines the Plugin Handler Interface. Classes that implement this handler must provide the methods and attributes defined below.

Implementations do not subclass from interfaces.

Usage:

from cement2.core import plugin

class MyPluginHandler(object):
    class Meta:
        interface = plugin.IPlugin
        label = 'my_plugin_handler'
    ...
load_plugin(plugin_name)

Load a plugin whose name is ‘plugin_name’.

Required Arguments:

plugin_name
The name of the plugin to load.
load_plugins(plugin_list)

Load all plugins from plugin_list.

Required Arguments:

plugin_list
A list of plugin names to load.
cement2.core.plugin.plugin_validator(klass, obj)

Validates an handler implementation against the IPlugin interface.

cement2.core.cache

Cement core cache module.

class cement2.core.cache.CementCacheHandler(*args, **kw)

Base class that all Cache Handlers should sub-class from.

class cement2.core.cache.ICache

This class defines the Cache Handler Interface. Classes that implement this handler must provide the methods and attributes defined below.

Implementations do not subclass from interfaces.

Usage:

from cement2.core import cache

class MyCacheHandler(object):
    class Meta:
        interface = cache.ICache
        label = 'my_cache_handler'
    ...
delete(key)

Deletes a key/value from the cache.

Return: True

get(key, fallback=None)

Get the value for a key in the cache. If the key does not exist or the key/value in cache is expired, this functions must return None.

Required Arguments:

key
The key of the value stored in cache

Optional Arguments:

fallback
The value that is returned if the cache is expired or the key does not exist.

Return: unknown (whatever the value is in cache, or the ‘fallback’)

purge()

Clears all data from the cache.

set(key, value, time=None)

Set the key/valuue in cache for ‘time’.

Required Arguments:

key
The key of the value to store in cache.
value
The value of that key to store in cache.

Optional Arguments:

time
A one-off expire time. If no time is given, then a default value is used (determined by the implementation).

Return: None

cement2.core.cache.cache_validator(klass, obj)

Validates an handler implementation against the ICache interface.

cement2.core.util

Cement util module.

cement2.core.util.abspath(path)

Wrapper to return the absolute path of a given path.

cement2.core.util.is_true(item)

Given a value, determine if it is one of [True, ‘True’, ‘true’, 1, ‘1’].