Cement core argument module.
Base class that all Argument Handlers should sub-class from.
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 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 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
Validates a handler implementation against the IArgument interface.
Cement core backend module.
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)
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')
Cement core config module.
Base class that all Config Handlers should sub-class from.
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 a new section if it doesn’t exist.
Required Arguments:
- section
- The [section] label to create.
Return: None
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
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
Return a list of configuration sections. These are designated by a [block] label in a config file.
Return: list
Returns whether or not the section exists.
Return: bool
Return a list of configuration keys from section.
Required Arguments:
- section
- The config [section] to pull keys from.
Return: list
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 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 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
Validates a handler implementation against the IConfig interface.
Cement core controller module.
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."
...
This is the default action if no arguments (sub-commands) are passed at command line.
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') ),
]
Validates a handler implementation against the IController interface.
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()")
Cement core exceptions module.
Generic errors.
Signal errors.
Cement core extensions module.
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 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 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’].
Validates an handler implementation against the IExtension interface.
Cement core application module.
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()
A shortcut for self.args.add_argument.
Close the application. This runs the cement_on_close_hook() allowing plugins/extensions/etc to ‘cleanup’ at the end of program execution.
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().
A shortcut for self.args.parsed_args.
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).
This function wraps everything together (after self._setup() is called) to run the application.
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 application config settings.
Catch a signal, run the cement_signal_hook, and then raise an exception allowing the app to handle logic elsewhere.
This function is deprecated. Please use CementApp() directly.
Cement core handler module.
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.
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)
Test whether a handler type is defined.
Required Arguments:
- handler_type
- The name or ‘type’ of the handler (I.e. ‘logging’).
Returns: bool
Deprecated as of 1.9.5. Use handler.registered().
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’))
Return a list of handlers for a given type.
Required Arguments:
- handler_type
- The type of handler (i.e. ‘output’)
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)
Check if a handler is registered.
Required Arguments:
- handler_type
- The type of handler
- handler_label
- The label of the handler
Returns: Boolean
Cement core hooks module.
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')
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
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
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
...
Cement core interface module.
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.
Cement core log module.
Base class that all Log Handlers should sub-class from.
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 all existing loggers.
Log to the ‘DEBUG’ facility.
Required Arguments:
- msg
- The message to log.
Log to the ‘ERROR’ facility.
Required Arguments:
- msg
- The message to log.
Log to the ‘FATAL’ facility.
Required Arguments:
- msg
- The message to log.
Log to the ‘INFO’ facility.
Required Arguments:
- msg
- The message to log.
Return a string representation of the log level.
Set the log level. Must except one of: ‘INFO’, ‘WARN’, ‘ERROR’, ‘DEBUG’, or ‘FATAL’.
Log to the ‘WARN’ facility.
Required Arguments:
- msg
- The message to log.
Validates an handler implementation against the ILog interface.
Cement core output module.
Base class that all Output Handlers should sub-class from.
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 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
Validates an handler implementation against the IOutput interface.
Cement core plugins module.
Base class that all Plugin Handlers should sub-class from.
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 a plugin whose name is ‘plugin_name’.
Required Arguments:
- plugin_name
- The name of the plugin to load.
Load all plugins from plugin_list.
Required Arguments:
- plugin_list
- A list of plugin names to load.
Validates an handler implementation against the IPlugin interface.
Cement core cache module.
Base class that all Cache Handlers should sub-class from.
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'
...
Deletes a key/value from the cache.
Return: True
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’)
Clears all data from the cache.
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
Validates an handler implementation against the ICache interface.
Cement util module.
Wrapper to return the absolute path of a given path.
Given a value, determine if it is one of [True, ‘True’, ‘true’, 1, ‘1’].