# Cement Developer Guide

## What is Cement?

Cement is an advanced application framework for Python, with a primary focus on Command Line Interfaces (CLI). Its goal is to introduce a standard, and feature-full platform for both simple and complex command line applications as well as support rapid development needs without sacrificing quality. Cement is flexible, and its use cases span from the simplicity of a micro-framework to the complexity of a mega-framework. Whether its a single file script, or a multi-tier application, Cement is the foundation you've been looking for.

The first commit to Git was on Dec 4, 2009. Since then, the framework has seen several iterations in design, and has continued to grow and improve since its inception. Cement is the most stable, and complete framework for command line and backend application development.

## Core Features

Cement core features include (but are not limited to):

* Core pieces of the framework are customizable via handlers/interfaces
* Extension handler to easily extend framework functionality
* Config handler merges defaults, multiple files, and environment variables into one config
* Argument handler parses command line arguments and options
* Log handler supports logging to console and file
* Plugin handler provides the ability to easily extend your application
* Output handler renders data to the end-user (often via template handler backends)
* Template handler renders content and file templates
* Cache handler adds caching support for improved performance or key/value storage
* Controller handler supports sub-commands, and nested/embedded controllers
* Hook support adds a bit of magic to apps and also ties into framework
* Zero external dependencies\* (not including optional extensions)
* 100% test coverage using `pytest` and `coverage`
* 100% PEP8 and style compliant using `flake8`
* Extensive Developer Guide and API Reference Documentation
* Tested on Python 3.7+
* Does not support Python 2.x

*Some optional extensions that are shipped with the mainline Cement sources do require external dependencies. It is the responsibility of the application developer to include these dependencies along with their application, as Cement explicitly does not include them.*

## License

The Cement Framework is Open Source and is distributed under the [BSD License (three clause)](https://opensource.org/licenses/BSD-3-Clause). Copyright (c) 2009 Data Folk Labs, LLC. All rights reserved.

## Projects Built on Cement™

The following are some notable projects that are Built on Cement™:

* [Amazon Elastic Beanstalk CLI](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3.html) ([PYPI](https://pypi.python.org/pypi/awsebcli))
* [Easy Engine](https://easyengine.io/) ([GitHub](https://github.com/EasyEngine/easyengine))
* [SentientHome](https://github.com/fxstein/SentientHome)
* [Pubkey](https://github.com/fxstein/pubkey)
* [HCE Project](http://hce-project.com/)
* [QLDS Manager](https://qlds-manager.readthedocs.io/en/stable/index.html) ([GitHub](https://github.com/rzeka/QLDS-Manager))

A more complete list of projects that depend on Cement can be found at [Librario.io](https://libraries.io/pypi/cement/dependents). If you are building a project on the Cement Framework and would like to see your company or project listed here [please create an issue and/or pull request on GitHub](https://github.com/datafolklabs/cement/).


# Release Information


# What's New!

Overview of notable features and major changes in the latest release.

## Notable Features and Changes

### Better Documentation

A lot of time and effort has gone into revamping the developer documentation, which includes:

* Separation of Developer Guide (this) and [API Reference](http://cement.readthedocs.io/en/3.0/)
* Complete [framework overview](/getting-started/framework-overview) and [beginner tutorial](/getting-started/beginner-tutorial) to get started building your first application
* List of [terminology](/terminology) used throughout the framework and documentation
* Thorough guide of all [builtin extensions](/extensions)

### Simplified API Naming Conventions and Usage

The naming conventions and library paths in Cement 2 were laborious to type and remember. Now all modules/methods/etc are importable from `cement` namespace directly, and the naming is simplified (ex: `CementApp` is now `App`, `CementHandler` is now `Handler`, etc).

```python
from cement import App, Controller, ex

class Base(Controller):
    class Meta:
        label = 'base'

    @ex(help='this is a command')
    def cmd1(self):
        print('Inside Base.cmd1()')

class MyApp(App):
    class Meta:
        label = 'myapp'
        handlers = [Base]
```

### Developer Tools CLI

The [Cement Developer Tools](/getting-started/developer-tools) allow developers to quickly generate projects, plugins, extensions, and scripts:

```
$ cement generate project ./myapp
INFO: Generating cement project in ./myapp/

$ cement generate plugin ./myapp/plugins/
INFO: Generating cement plugin in ./myapp/plugins/

$ cement generate extension ./myapp/ext/
INFO: Generating cement extension in ./myapp/ext/

$ cement generate script .
INFO: Generating cement script in .
```

### Clearer Interface Definition and Implementation

In Cement 2, the design of the interface and handler system was not easy to follow for new developers to the framework. It was also loosely modeled after ZopeInterface, and that may have lead to some odd naming conventions (IMeta, IMyInterface, etc), and an implementation that just felt weird.

Interfaces are now defined using the standard library's [Abstract Base Class](https://docs.python.org/3/library/abc.html) module per the [request of the community](https://github.com/datafolklabs/cement/issues/192), moving the framework away from oddities and more toward common Python standards.

### Docker / Docker Compose Support

Cement now includes a fully functioning docker setup out-of-the-box for local development of the framework that includes all dependencies, and dependency services like Redis, Memcached, etc.

Getting up and running is as simple as running the following:

```
$ make dev

|> cement <| src #
```

This drops you into a shell within a docker container, and environment so that everything required to dev, and test is ready to roll:

```
|> cement <| src # make test

|> cement <| src # make docs
```

*See the* `Makefile` *for more common development tasks (for framework development).*

### Environment Variable Overrides

Cement now supports the ability to override all config object settings via their associated environment variables. For example:

{% tabs %}
{% tab title="myapp.py" %}

```python
from cement import App, init_defaults

CONFIG = init_defaults('myapp')
CONFIG['myapp']['foo'] = 'bar'

class MyApp(App):
    class Meta:
        label = 'myapp'
        config_defaults = CONFIG

with MyApp() as app:
    app.run()
    foo = app.config.get('myapp', 'foo')
    print('Foo => %s' % foo)
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
Foo => bar

$ export MYAPP_FOO='not-bar'

$ python myapp.py
Foo => not-bar
```

{% endtab %}
{% endtabs %}

Environment variables are logically mapped to configuration settings based on their config keys and are prefixed with `MYAPP_` (based on the label of the app). So:

* `config['myapp']['foo']` => `$MYAPP_FOO`
* `config['some_section']['foo']` => `$MYAPP_SOME_SECTION_FOO`

## New Interfaces

| **Interface**                               | Description                                                                                                                                                                                                  |
| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [**Template**](/core-foundation/templating) | Rendering of template data (content, files, etc).  Existing output handler extensions were also updated to include an associated template handler (`MustacheTemplateHandler`, `Jinja2TemplateHandler`, etc). |

## New Extensions

| Extension                            | Description                                                                                                                                                                                                                                                                                              |
| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [**Print**](/extensions/print)       | Used primarily in development as a replacement for standard `print()`, allowing the developer to honor framework features like `pre_render` and `post_render` hooks.                                                                                                                                     |
| [**Scrub**](/extensions/scrub)       | Adds the ability to easily obfuscate sensitive data from rendered output (think IP addresses, credit card numbers, etc)                                                                                                                                                                                  |
| [**Generate**](/extensions/generate) | Adds the ability for application developers to add a `generate` controller to their application, and include any number of source templates to generate from.  Think `myapp generate plugin` for third party developers to create plugins for your application from a fully-functional working template. |


# Upgrading

## Upgrading from Cement 2

There is currently no upgrade path directly from Cement 2. Cement 3 is the first iteration of a new/modified codebase and as such breakage was intentionally not a concern.

In general, usage is very similar. However, paths to classes and class names may have changed and will need to be modified. If not married to your existing application layout/design/etc, it would be recommended to start a new project using the `cement generate` developer tools, and move code into it piece by piece.

Data Folk Labs, LLC (the creators of Cement) do offer consulting and development services, and could evaluate the migration of a Cement 2 app over to Cement 3. Please contact us if that is something you'd be interested to inquire about: [team@datafolklabs.com](mailto:%20team@datafolklabs.com).


# ChangeLog

## 3.0.16 - July 13, 2026

This release modernizes Cement against the current Python ecosystem while holding the 3.0.x public API stable. Python 3.8 and 3.9 are dropped (EOL) and the supported matrix is now Python 3.10–3.14. Every deprecation in this release is warn-only, with removals signposted for 3.2.0 so downstream apps have a clear upgrade window. A new automated GitHub Actions release workflow replaces the manual release checklist, and the `cement generate` project and todo-tutorial templates are now fully typed, PEP 517-buildable, and green under `make comply` and `make test` out of the box.

Bugs:

* `[core]` Add an explicit `__all__` to `cement/__init__.py` so `from cement import *` exports only the intended public surface (App, TestApp, Interface, Handler, Controller, the framework exceptions, and the documented helpers) instead of leaking every transitively imported name — #756
* `[core.foundation]` Honor `Meta.config_section` (not `Meta.label`) when applying the `extensions` config override, mirroring the `template_dirs` fix — resolves #777
* `[ext.smtp]` Fix `timeout` being passed as `local_hostname` in the SMTP constructors
* `[ext.smtp]` Fix a stale variable reference in `_get_params` for per-message headers
* `[ext.smtp]` Fix an SMTP connection leak when a send fails with an exception
* `[ext.smtp]` Only log on send errors (was logging unconditionally on every send)
* `[ext.smtp]` Fix header encoding being incorrectly affected by the `body_encoding` setting
* `[cli]` Generated `cement generate project` output now builds under pip's default PEP 517 isolation on Python 3.10+ (the legacy `setup.py` self-imported the package being built, which fails in isolated build envs)
* `[core.handler]` Resolve a mypy union-attr false-positive in handler resolution
* `[ext.redis]` Resolve mypy union-attr/arg-type/misc errors surfaced by redis 7 typing changes
* `[ext.watchdog]` Drop now-unused `# type: ignore` comments on the Observer calls — watchdog 6 ships precise type stubs
* `[utils.fs]` Restore `os.path` semantics in `abspath()` — preserve symlink paths and fall through on unknown `~user` prefixes (regression from the Phase 03 pathlib migration; restores the 3.0.x BC contract)
* `[dev]` Use explicit `encoding='utf-8'` in `scripts/audit-public-api.py` so the `make audit-public-api` gate is portable across non-UTF-8 locales
* `[dev]` Fix `scripts/cli-smoke-test.sh` capturing a CRLF-tainted temp path from `docker exec -t` that broke pdm/venv on the first Python version (drop `-t` on that one capture)
* `[dev]` Fix `scripts/cli-smoke-test.sh` `pdm install` failing to resolve the unreleased dev cement pin by injecting a local find\_links source (`/src/dist`); harness-only, the project gates are unaffected
* `[core.interface]` Widen the `InterfaceManager.get` `fallback` parameter back to `Any` to match the documented contract (it was mechanically narrowed by the Phase 03 UP045 sweep; the runtime always accepted arbitrary fallback values)
* `[ext.smtp]` Type the message body and `**params` correctly across `send`/`_make_message` and the related private helpers (new private `_BodyType` alias reflects the dict body shape); drop nine now-unused `# type: ignore` suppressions. Public API byte-identical
* `[utils.shell]` Correct the `cmd`/`exec_cmd` return annotations from `str` to `bytes` — `subprocess.Popen` returns bytes by default and the existing tests assert byte literals; docstrings now point at `text=True`/`encoding=` for `str` output (runtime unchanged)
* `[utils.shell]` Correct the `Prompt.Meta.options` annotation from `dict | None` to `list[str] | None` to match actual runtime usage
* `[ext.yaml]` Use explicit `template: str | None = None` (PEP 484 / RUF013) in `render()` and drop the signature-line `# type: ignore`
* `[ext.mustache]` Use explicit `template: str | None = None` (PEP 484 / RUF013) in `render()`; scope the remaining `# type: ignore` to the load callsite
* `[utils.misc]` Make `MinimalLogger.__init__` idempotent — guard the console-handler add on `not self.backend.handlers` so repeated `minimal_logger(ns)` calls no longer stack duplicate handlers (which caused log output to repeat N times)
* `[ext.daemon]` Remove a duplicate module-scope `LOG = minimal_logger(__name__)` rebind
* `[core.template]` Replace the fragile bare `assert` in `TemplateHandler.copy()` with an explicit `NotADirectoryError` (the assert was stripped under `python -O` and passed for regular files). **Compatibility note:** the raised exception type changes from `AssertionError` to `NotADirectoryError`
* `[core.interface]` String-quote a `list[str]` return annotation for autodoc compatibility
* `[core.deprecations]` Drop a trailing period from the `3.0.10-1` deprecation message (it rendered as `..` once `deprecate()` appended its suffix)
* `[dev]` `make docs` zero-warnings gate now uses `&&` (was `;`) so it fails on Sphinx warnings
* `[ext.generate]` Fix the `variables` default from `{}` to `[]` — the generate flow iterates `variables` as a list of dicts
* `[ext.generate]` Narrow the dynamic-template-module `except` to `(AttributeError, ModuleNotFoundError)` with a name guard so transitive import errors in a user's template module propagate normally
* `[ext.generate]` `type: boolean` variables now emit a real Python bool at the top level (`data[name]`) so `{% if feature_x %}` works; boolean prompts use a vars-style `[(Y)es/(N)o]` format in a single declaration-order pass — resolves #782 (the `features:` namespace is removed)
* `[cli]` Generated `cement generate todo-tutorial` output now builds under PEP 517 isolation on Python 3.10+ (mirrors the `generate project` fix) — #735
* `[cli]` Fix a `NameError` in generated `todo/main.py` (now `except TodoError as e:`) — #735
* `[cli]` Fix a false-green assertion in the generated project test template — a membership check replaces `str.find()`, which returned a truthy `-1` and never failed — #735
* `[cli]` Generated todo-tutorial imports are isort-clean and its `[tool.ruff]` is scoped to `todo/`, so the shipped `make comply` is green out of the box — #735
* `[cli]` Constrain the cement dependency in generated `project` and `todo-tutorial` templates to a compatible 3.0.x range (`~=3.0.0` / `>=3.0,<3.1`) so freshly generated projects install even when generated by an unreleased dev cement — #735

Features:

* `[core.foundation]` Support config override of `App.Meta.template_dirs` via the `[<app>]` section — accepts a list (native-list config handlers) or a comma-separated string (the INI handler), parallel to the existing `extensions` handling.
  * [Issue #746](https://github.com/datafolklabs/cement/issues/746)
* `[ext.generate]` Add optional features support to generate templates — conditional variables, exclude/ignore patterns, and order-independent `requires` dependency resolution (with transitive cascade).
  * [Issue #743](https://github.com/datafolklabs/cement/issues/743)
* `[ext.generate]` Add `prompt_mode: select` for multi-valued feature prompts — a numbered picker dispatching the chosen value into one of N `options` branches, each with its own `ignore`/`exclude`/`variables`; defaults to `boolean` (byte-identical when absent).
  * [Issue #779](https://github.com/datafolklabs/cement/issues/779)
* `[ext.generate]` Add `type: choice` template variables — a numbered picker that emits the chosen option string at the top level; `options:` accepts scalars or `{value, prompt}` objects with per-option effects in `extend:` rules; misconfig is fail-fast `ValueError`.
* `[ext.generate]` `type: boolean` `prompt:` is now polymorphic — an object form `{text, accept, reject}` lets the template author own the prompt text and supply the token lists that map input to a real bool; unmatched input aborts with `Invalid Response`.
* `[ext.generate]` `extend.when` now composes scalar-equality, in-list membership, and string-regex match forms (all matching rules fire) with nested depth-first `extend.variables`; a new top-level `requires:` key gates variables using the same vocabulary, AND-ed and resolved order-independently, defaulting gated-out variables so templates never `KeyError`. Also addresses the PR #780 review feedback (features prompt after vars, custom prompt text, vars-style input).
  * [Issue #782](https://github.com/datafolklabs/cement/issues/782)
  * [PR #780](https://github.com/datafolklabs/cement/pull/780)
* `[ext.argparse]` Add a read-only `_command_meta` property on `ArgparseController` so an exposed command can read its own `CommandMeta` from inside its body; returns `None` outside a dispatched command and never raises. Additive — the `func()` dispatch signature is unchanged.
  * [Issue #670](https://github.com/datafolklabs/cement/issues/670)
* `[ext.argparse]` Add a companion read-only `_default_command_meta` property that resolves the controller's default sub-command meta (via `Meta.default_func`); returns `None` when there is no exposed default and never raises.
  * [Issue #670](https://github.com/datafolklabs/cement/issues/670)
* `[utils.misc]` Add an optional `CEMENT_FRAMEWORK_LOG_FILE` env var — when framework logging is enabled, debug output is also written to the given file. Purely additive: no duplicate handlers on repeat calls, and an invalid path is ignored rather than raising.
  * [Issue #593](https://github.com/datafolklabs/cement/issues/593)

Refactoring:

* `[ext.generate]` Remove the unreleased `features:` schema wholesale — everything it expressed is now a `type: boolean`/`type: choice` variable carrying `extend:`/`requires:`; the legacy compatibility bridge is deleted (#782)
* `[dev]` Migrate the `demo/generate-features/` webapp template to the unified `type:`/`extend:`/`requires:` schema and demonstrate the #782 fix (top-level `{% if docker %}` / `{% if web_framework == ... %}`)
* `[ext.smtp]` PEP 8 naming, idiomatic string methods, and cleaner type validation
* `[ext.smtp]` Refactor `_make_message` into focused private methods
* `[ext.smtp]` Simplify X-header normalization and preserve original casing
* `[dev]` Python 3.14 default development target
* `[dev]` Remove support for Python 3.8 (EOL)
* `[dev]` Remove support for Python 3.9 (EOL)
* `[cli]` Migrate the `cement generate project` template from setuptools+`setup.py` to pdm-backend with full PEP 621 metadata and PEP 735 dev deps; generated `version.py` no longer imports cement at build time
* `[cli]` Generated project `README.md`/`Makefile` now document Python 3.10+ and PDM, use `pip install .` for end users, and rename the `virtualenv` target to `setup` (`pdm install`)
* `[core]` Modernize type annotations to PEP 585 builtin generics (UP006: `List`→`list`, `Dict`→`dict`, `Tuple`→`tuple`, `Type`→`type`); prune orphaned `typing` re-exports
* `[core]` Modernize union types to PEP 604 syntax (UP007: `Union[X, Y]`→ `X | Y`); prune orphaned `typing.Union` imports
* `[core]` Modernize Optional types to PEP 604 syntax (UP045: `Optional[X]`→`X | None`); prune orphaned `typing.Optional` imports
* `[core]` Move `Callable`/`Generator` imports from `typing` to `collections.abc` (UP035)
* `[core]` Convert printf-style format strings to modern format (UP031); protected `.format(**template_dict)` template callsites preserved
* `[core]` Drop redundant `(object)` base classes (UP004)
* `[core]` Simplify `super()` calls to the zero-arg form (UP008)
* `[core]` Drop the redundant `'r'` mode argument from `open()` calls (UP015)
* `[core]` Replace the `IOError` alias with `OSError` (UP024)
* `[dev]` Drop the legacy `u"..."` unicode literal prefix in test code (UP025)
* `[dev]` Replace the deprecated `mock` import with `unittest.mock` (UP026)
* `[core]` Replace `for x in iterable: yield x` with `yield from` (UP028)
* `[core]` Convert `.format()` calls to f-strings (UP032); protected template callsites preserved
* `[core]` Tighten `Any` types in `cement/core/` where narrower types are provably correct; surviving `Any` carries inline justification
* `[dev]` Refresh CONVENTIONS.md type-annotation guidance to PEP 585 / PEP 604 syntax
* `[core]` Wrap long log/error messages (E501) and reorder imports (I001) surfaced by the UP sweeps
* `[core]` Drop `from __future__ import annotations` from all 29 `cement/` files (native on 3.10+); convert affected forward references to PEP 484 string annotations
* `[utils.fs]` Migrate `cement/utils/fs.py` internals to pathlib while preserving `str` return boundaries (public surface unchanged)
* `[core.config]` Migrate the `config.py` `parse_file` os.path callsite to pathlib; retain `import os` as a no-op to keep the public surface intact
* `[core.foundation]` Migrate the `foundation.py` `_find_config_files` os.path callsite to pathlib; retain the public `join = os.path.join` alias and leave protected template callsites untouched
* `[core.template]` Migrate `template.py` os.path internals to pathlib; retain the `os.walk(src)` callsite (no direct pathlib equivalent for the triple-tuple loop)
* `[dev]` Audit `pragma: nocover` sites in `cement/core/` with locked-vocabulary category labels
* `[dev]` Audit `pragma: nocover` sites in `cement/ext/` (first half) with locked-vocabulary category labels
* `[dev]` Audit `pragma: nocover` sites in `cement/ext/` (second half) with locked-vocabulary category labels
* `[dev]` Audit `pragma: nocover` sites in `cement/cli/` and `cement/utils/` with locked-vocabulary category labels
* `[core.deprecations]` Pin the `3.0.10-1` and `3.0.16-1` deprecation removal versions to v3.2.0
* `[ext.logging]` Tighten the FATAL deprecation removal version in docstrings
* `[ext.smtp]` Document the `send()` bool-return removal in v3.2.0
* `[cli]` Migrate the `cement generate todo-tutorial` template to pdm-backend with full PEP 621 metadata and a PEP 735 dev group (mirrors `generate project`; #735)
* `[cli]` Ship `[tool.ruff]`/`[tool.mypy]`/`[tool.pytest]` gate config in the generated project and todo-tutorial so `make comply`/`make test` are green out of the box (#735)
* `[cli]` Type-annotate all generated templates (project/script/extension/plugin/todo) and modernize idioms to f-strings (#735)

Misc:

* `[ci]` Add GitHub Actions PR CI (`build_and_test.yml`) running the test suite on pull requests with minimal permissions — #757
* `[ci]` Add an automated release workflow (`release.yml`) — tag-triggered: preflight guard → gate suite → isolated build → TestPyPI publish + 5-Python install smoke → environment-gated OIDC PyPI publish → post-approval fan-out (Docker Hub multi-arch, `stable/3.0.x` sync, RTD re-point, GitHub Release, dev-bump PR, checklist issue); `workflow_dispatch` runs it as a dry run
* `[ci]` Refactor the PR gate chain into a reusable `gates.yml` (`workflow_call`) shared by PR CI and release; wire the matrix Python versions; add (disabled) Windows core-test and macOS/Windows native smoke gates
* `[dev]` Add release dev-tooling scripts: `testpypi-smoke.py`, `cli-smoke-native.py`, `bump_dev_version.py`
* `[dev]` Add devbox/direnv development-environment configuration for reproducible local setup
* `[ext.smtp]` Isolate test defaults to prevent cross-test state pollution
* `[dev]` Bump ruff to 0.15.x; codify rule sets explicitly and resolve all surfacing lint findings
* `[dev]` Bump mypy to \~=1.20.2 and codify the type-check surface
* `[dev]` Bump pytest 9.0.3, pytest-cov 7.1.0, coverage 7.13.5
* `[dev]` Add a `make cli-smoke-test` target — generated-project install smoke across Python 3.10–3.14 in Docker
* `[dev]` Bump the dev/extras lockfile to current non-breaking versions (redis 7.4, watchdog 6.0, tabulate 0.10, sphinx 8.1, requests 2.33, others)
* `[dev]` Wire the 100% coverage gate via `[tool.coverage.report]` `fail_under` + `--cov-fail-under`
* `[ci]` Pin GitHub Actions to exact tags
* `[ci]` Add PyPy 3.11 to the CI test matrix (alongside PyPy 3.10)
* `[ci]` Enable Dependabot for the github-actions ecosystem (weekly)
* `[ci]` Add a `workflow_dispatch` trigger to `pdm.yml`
* `[dev]` Add a `make audit-public-api` target + AST-walk public-surface enumerator + baseline snapshot
* `[dev]` Enable ruff `UP` (pyupgrade) and `FA` (flake8-future-annotations) families
* `[dev]` Capture the Phase 03 Any-in-core / pragma / pathlib baselines in `03-VERIFICATION.md`
* `[dev]` Finalize Phase 03 verification (all D-24 conjuncts green; REFACTOR-01..04 + COV-01..03 satisfied)
* `[dev]` Complete Phase 03 (Internal Refactor & Coverage Hardening); ROADMAP updated
* `[docs]` Drop the unsupported `logo` theme option from the Sphinx config
* `[docs]` Remove the orphan `docs/source/api/index.rst`
* `[docs]` Rename `display_version` to `version_selector` (sphinx\_rtd\_theme 3.x)
* `[docs]` Fix inline-literal RST in the `shell.cmd()` docstring
* `[docs]` Add a top-level DEPRECATIONS.md mirroring the GitBook narrative
* `[dev]` Wire `-W` into `make docs` (zero-warnings gate)
* `[docs]` Drop the Travis CI link/badge (CI moved to GitHub Actions)
* `[docs]` Align CONTRIBUTING with Conventional Commits + atomic-per-concern
* `[docs]` Expose `cement.core.deprecations` in the Sphinx API reference (was missing)
* `[docs]` Fix a `stderror` → `stderr` typo in the `cement.utils.shell` `cmd()`/`exec_cmd()` Returns docstrings
* `[docs]` Remove an orphaned `[Commit Guidelines]` reference-link definition from `.github/CONTRIBUTING.md`
* `[dev]` Extend the CI `cli-smoke-test` to gate the generated project's own `make comply`/`make test` and to build/install the generated todo-tutorial (#735)
* `[dev]` Add a generated-todo ruff-clean regression guard (`test_generate_todo_ruff_clean`) (#735)

Deprecations:

* `[ext.smtp]` `SMTPMailHandler.send()` returning `bool` is deprecated (warn-only); it will return a `senderrs` dict, with removal targeted for v3.2.0

## # 3.0.14 - May 5, 2025

Bugs:

* `[ext_jinja2]` Refactor hard-coded reference to `jinja2` template handler.
  * [Issue #749](https://github.com/datafolklabs/cement/issues/749)
* `[ext_smtp]` Misc fixes and updates to better support content types.
  * [PR #742](https://github.com/datafolklabs/cement/pull/742)

Features:

* None

Refactoring:

* None

Misc:

* None

Deprecations:

* None

## 3.0.12 - Nov 10, 2024

Bugs:

* None

Features:

* None

Refactoring:

* `[dev]` Refactor String Substitutions (`%s`) with F-Strings
  * [Issue #733](https://github.com/datafolklabs/cement/issues/733)
* `[dev]` Allow line lengths up to 100 characters (previously 78)
* `[dev]` Modernize Packaging (pyproject.toml, PDM)
  * [Issue #680](https://github.com/datafolklabs/cement/issues/680)
  * [PR #681](https://github.com/datafolklabs/cement/pull/681)
* `[dev]` Implement Ruff for Code Compliance (replaces Flake8)
  * [Issue #671](https://github.com/datafolklabs/cement/issues/671)
  * [PR #681](https://github.com/datafolklabs/cement/pull/681)
* `[dev]` Remove Python 3.5, 3.6, 3.7 Docker Dev Targets
* `[dev]` Added Python 3.13 Dev Target
* `[dev]` Testing now requires typing compliance (`make test` -> `make comply-mypy`)
* `[dev]` Type Annotations (related: [PR #628](https://github.com/datafolklabs/cement/pull/628))
  * `[core.arg]` [Issue #692](https://github.com/datafolklabs/cement/issues/692)
  * `[core.cache]` [Issue #693](https://github.com/datafolklabs/cement/issues/693)
  * `[core.config]` [Issue #694](https://github.com/datafolklabs/cement/issues/694)
  * `[core.controller]` [Issue #695](https://github.com/datafolklabs/cement/issues/695)
  * `[core.deprecations]` [Issue #696](https://github.com/datafolklabs/cement/issues/696)
  * `[core.exc]` [Issue #697](https://github.com/datafolklabs/cement/issues/697)
  * `[core.extension]` [Issue #698](https://github.com/datafolklabs/cement/issues/698)
  * `[core.foundation]` [Issue #699](https://github.com/datafolklabs/cement/issues/699)
  * `[core.handler]` [Issue #700](https://github.com/datafolklabs/cement/issues/700)
  * `[core.hook]` [Issue #700](https://github.com/datafolklabs/cement/issues/701)
  * `[core.interface]` [Issue #702](https://github.com/datafolklabs/cement/issues/702)
  * `[core.log]` [Issue #703](https://github.com/datafolklabs/cement/issues/703)
  * `[core.mail]` [Issue #704](https://github.com/datafolklabs/cement/issues/704)
  * `[core.meta]` [Issue #705](https://github.com/datafolklabs/cement/issues/705)
  * `[core.output]` [Issue #706](https://github.com/datafolklabs/cement/issues/706)
  * `[core.plugin]` [Issue #707](https://github.com/datafolklabs/cement/issues/707)
  * `[core.template]` [Issue #708](https://github.com/datafolklabs/cement/issues/708)
  * `[ext.alarm]` [Issue #709](https://github.com/datafolklabs/cement/issues/709)
  * `[ext.argparse]` [Issue #710](https://github.com/datafolklabs/cement/issues/710)
  * `[ext.colorlog]` [Issue #711](https://github.com/datafolklabs/cement/issues/711)
  * `[ext.configparser]` [Issue #712](https://github.com/datafolklabs/cement/issues/712)
  * `[ext.daemon]` [Issue #713](https://github.com/datafolklabs/cement/issues/713)
  * `[ext.dummy]` [Issue #714](https://github.com/datafolklabs/cement/issues/714)
  * `[ext.generate]` [Issue #715](https://github.com/datafolklabs/cement/issues/715)
  * `[ext.jinja2]` [Issue #716](https://github.com/datafolklabs/cement/issues/716)
  * `[ext.json]` [Issue #717](https://github.com/datafolklabs/cement/issues/717)
  * `[ext.logging]` [Issue #718](https://github.com/datafolklabs/cement/issues/718)
  * `[ext.memcached]` [Issue #719](https://github.com/datafolklabs/cement/issues/719)
  * `[ext.mustache]` [Issue #720](https://github.com/datafolklabs/cement/issues/720)
  * `[ext.plugin]` [Issue #721](https://github.com/datafolklabs/cement/issues/721)
  * `[ext.print]` [Issue #722](https://github.com/datafolklabs/cement/issues/722)
  * `[ext.redis]` [Issue #723](https://github.com/datafolklabs/cement/issues/723)
  * `[ext.scrub]` [Issue #724](https://github.com/datafolklabs/cement/issues/724)
  * `[ext.smtp]` [Issue #725](https://github.com/datafolklabs/cement/issues/725)
  * `[ext.tabulate]` [Issue #726](https://github.com/datafolklabs/cement/issues/726)
  * `[ext.watchdog]` [Issue #727](https://github.com/datafolklabs/cement/issues/727)
  * `[ext.yaml]` [Issue #728](https://github.com/datafolklabs/cement/issues/728)
  * `[utils.fs]` [Issue #688](https://github.com/datafolklabs/cement/issues/688)
  * `[utils.misc]` [Issue #689](https://github.com/datafolklabs/cement/issues/689)
  * `[utils.shell]` [Issue #690](https://github.com/datafolklabs/cement/issues/690)
  * `[utils.version]` [Issue #691](https://github.com/datafolklabs/cement/issues/691)

Misc:

* \[cli] Move CLI dependencies to `cement[cli]` extras package, and remove included/nexted `contrib` sources. See note on 'Potential Upgrade Incompatibility'
  * [Issue #679](https://github.com/datafolklabs/cement/issues/679)

Deprecations:

* None

Special Recognitions:

Many thanks to [@sigma67](https://github.com/sigma67) for their contributions in modernizing the packaging system. Cement was started in 2009, and has some lingering technical debt that is now being addressed. Their contribution was a major help in moving off of setuptools and on to PDM and `pyproject.toml`, along with initial implementations of Ruff for a new generation of code compliance. I sincerely appreciate your help!

Many thanks to [@rednar](https://github.com/rednar) for their contributions toward adding type annotations in [PR #628](https://github.com/datafolklabs/cement/pull/628). This PR was too large to merge directly, but it is serving as a guide to finally begin work toward adding type annotations to Cement. This was a massive effort, and is very helpful to have this work available to guide the effort even if it will not be merged directly.

Potential Upgrade Incompatibility:

This update removes included `contrib` libraries that are dependencies for the `cement` command line tool to function (PyYAML, and Jinja2). The dependencies are now included via the `cement[cli]` extras package.

This is not an upgrade incompatibility in the core Cement code, and it would not affect any applications that are built on Cement. That said, it does have the potential to break any automation or other uses of the `cement` command line tool.

Resolution:

```
pip install cement[cli]
```

## 3.0.10 - Feb 28, 2024

Bugs:

* `[ext.logging]` Support `logging.propagate` to avoid duplicate log entries
  * [Issue #310](https://github.com/datafolklabs/cement/issues/310)
* `[core.foundation]` Quiet mode file is never closed
  * [Issue #653](https://github.com/datafolklabs/cement/issues/653)
* `[ext.smtp]` Ability to Enable TLS without SSL
  * [Issue #667](https://github.com/datafolklabs/cement/issues/667)
* `[ext.smtp]` Empty (wrong) addresses sent when CC/BCC is `None`
  * [Issue #668](https://github.com/datafolklabs/cement/issues/668)

Features:

* `[utils.fs]` Add Timestamp Support to fs.backup
  * [Issue #611](https://github.com/datafolklabs/cement/issues/611)
* `[ext.smtp]` Support for sending file attachements.
  * [PR #669](https://github.com/datafolklabs/cement/pull/669)
* `[ext.smtp]` Support for sending both Plain Text and HTML
  * [PR #669](https://github.com/datafolklabs/cement/pull/669)

Refactoring:

* `[core.plugin]` Deprecate the use of `imp` in favor of `importlib`
  * [Issue #386](https://github.com/datafolklabs/cement/issues/386)
* `[ext.smtp]` Actually test SMTP against a real server (replace mocks)

Misc:

* `[dev]` Add Smoke tests for Python 3.11, 3.12
* `[dev]` Make Python 3.12 the default development target
* `[dev]` Drop support for Python 3.7
  * [Issue #658](https://github.com/datafolklabs/cement/issues/658)
* `[docker]` Base official Docker image on Python 3.12
* `[utils.version]` Resolve deprecated `datetime.utcfromtimestamp()`
  * [Issue #661](https://github.com/datafolklabs/cement/issues/661)
* `[dev]` Add `comply-typing` to make helpers, start working toward typing.
  * [Issue #599](https://github.com/datafolklabs/cement/issues/661)
  * [PR #628](https://github.com/datafolklabs/cement/pull/628)
* `[dev]` Add `mailpit` service to docker-compose development config.

Deprecations:

* `[ext.logging]` Deprecate FATAL facility in favor of CRITICAL.
  * [Issue #533](https://github.com/datafolklabs/cement/issues/533)

## 3.0.8 - Aug 18, 2022

Bugs:

* `[cli]` Cement CLI broken on Python 3.10
  * [Issue #619](https://github.com/datafolklabs/cement/issues/619)
* `[cli]` Generated script returns version of Cement
  * [Issue #632](https://github.com/datafolklabs/cement/issues/632)
* `[cli]` Generated script should allow dash/underscore
  * [Issue #614](https://github.com/datafolklabs/cement/issues/614)
* `[core.foundation]` App.render() not suppressed in quiet mode
  * [Issue #636](https://github.com/datafolklabs/cement/issues/636)
* `[core.foundation]` Console log not suppressed by output handler override (JSON/YAML)
  * [Issue #637](https://github.com/datafolklabs/cement/issues/637)

Features:

* `[utils.shell]` Support `suppress` meta option on `Prompt` to suppress user input.
  * [Issue #621](https://github.com/datafolklabs/cement/issues/621)
* `[ext]` Use `extras_require` for optional extensions
  * [Issue #604](https://github.com/datafolklabs/cement/issues/604)

Refactoring:

* `[utils.misc]` Use SHA256 instead of MD5 in `rando()` to support Redhap/FIPS compliance
  * [Issue #626](https://github.com/datafolklabs/cement/issues/626)
* `[core.foundation]` Make quiet/debug options configurable
  * [Issue #613](https://github.com/datafolklabs/cement/issues/613)

Misc:

* `[dev]` Cement CLI smoke tests
  * [Issue #620](https://github.com/datafolklabs/cement/issues/620)
* `[dev]` Add Python 3.10 to Travis CI tests
  * [Issue #618](https://github.com/datafolklabs/cement/issues/618)
* `[core.deprecations]` Implement Cement deprecation warnings
  * [Issue #631](https://github.com/datafolklabs/cement/issues/631)

Deprecations:

* `[core.foundation]` Deprecate CEMENT\_FRAMEWORK\_LOGGING in favor of CEMENT\_LOG.
  * [Issue #638](https://github.com/datafolklabs/cement/issues/638)

## 3.0.6 - Dec 18, 2021

Bugs:

* `[ext.argparse]` Parser (`self._parser`) not accessible inside `_pre_argument_parsing` when `stacked_type = 'embedded'`
  * [Issue #569](https://github.com/datafolklabs/cement/issues/569)
* `[ext.configparser]` Overriding config options with environment variables doesn't work correctly with surrounding underscore characters
  * [Issue #590](https://github.com/datafolklabs/cement/issues/590)
* `[utils.fs]` Fix bug where trailing slash was not removed in `fs.backup()` of a directory.
  * [Issue #610](https://github.com/datafolklabs/cement/issues/610)
* `[cement.cli]` Generated README contains incorrect installation instructions.
  * [Issue #588](https://github.com/datafolklabs/cement/issues/588)

Features:

* None

Refactoring:

* `[ext.colorlog]` Support subclassing of ext\_colorlog.
  * [Issue #571](https://github.com/datafolklabs/cement/issues/571)

Misc:

* `[dev]` Update to Python 3.10 for default development / Docker version.
* `[dev]` Remove Python 3.5/3.6 from Travis CI tests.

## 3.0.4 - May 17, 2019

**Bugs:**

* `[ext.yaml]` YamlConfigHandler uses unsafe load method
  * [Issue #553](https://github.com/datafolklabs/cement/issues/553)
* `[ext.configparser]` Configparser 'getboolean' exception
  * [Issue #558](https://github.com/datafolklabs/cement/issues/558)

**Features:**

* `[utils.misc]` Support `y` as a truth boolean in `utils.misc.is_true`
  * [Issue #542](https://github.com/datafolklabs/cement/issues/542)

## 3.0.2 - November 6, 2018

**Bugs:**

* `[cli]` Generate Variable Mishap in Project Template
  * [Issue #532](https://github.com/datafolklabs/cement/issues/532)
* `[ext.generator]` Error class is malformed
  * [Issue #535](https://github.com/datafolklabs/cement/issues/535)
* `[core.template]` MemoryError during 'cement generate project'
  * [Issue #531](https://github.com/datafolklabs/cement/issues/531)
* `[core.foundation]` Contents of plugin\_dirs is printed to console
  * [Issue #538](https://github.com/datafolklabs/cement/issues/538)

**Features:**

* `[ext.argparse]` Command name override
  * [Issue #529](https://github.com/datafolklabs/cement/issues/529)

## 3.0.0 - Aug 21, 2018

**Bugs:**

* `[ext.redis]` Unable To Set Redis Host
  * [Issue #440](https://github.com/datafolklabs/cement/issues/440)
* `[ext.argparse]` Empty Sub-Commands List
  * [Issue #444](https://github.com/datafolklabs/cement/issues/444)
* `[core.foundation]` Handler Override Options Do Not Honor Meta Defaults
  * [Issue #513](https://github.com/datafolklabs/cement/issues/513)

**Features:**

* `[core]` Add Docker / Docker Compose Support
  * [Issue #439](https://github.com/datafolklabs/cement/issues/439)
* `[core]` Add ability to override the output handler used when `app.render()` is called.
  * [Issue #471](https://github.com/datafolklabs/cement/issues/471)
* `[ext.print]` Add the Print Extension to be used as a drop in replacement for the standard `print()`, but allowing the developer to honor framework features like `pre_render` and `post_render` hooks.
* `[ext.scrub]` Add Scrub Extension to easily obfuscate sensitive data from rendered output.
  * [Issue #469](https://github.com/datafolklabs/cement/issues/469)
* `[core]` Add ability to override config settings via environment variables.
  * [Issue #437](https://github.com/datafolklabs/cement/issues/437)
* `[ext.argparse]` Add ability to get list of exposed commands
  * [Issue #455](https://github.com/datafolklabs/cement/issues/455)
* `[core]` Add Template Interface
  * [Issue #464](https://github.com/datafolklabs/cement/issues/464)
* `[ext.mustache]` Add MustacheTemplateHandler
* `[ext.handlebars]` Add HandlebarsTemplateHandler
* `[ext.jinja2]` Add Jinja2TemplateHandler
* `[ext.generate]` Add Generate Extension
  * [Issue #487](https://github.com/datafolklabs/cement/issues/487)
* `[ext.logging]` Add `-l LEVEL` command line option to override log level
  * [Issue #497](https://github.com/datafolklabs/cement/issues/497)
* `[cli]` Add Cement CLI (includes ability to generate apps, plugins,

  &#x20; extensions, and scripts using the Generate Extension)

  * [Issue #490](https://github.com/datafolklabs/cement/issues/490)
* `[core]` Added clear separation between Interfaces and Handlers
  * [Issue #506](https://github.com/datafolklabs/cement/issues/506)
* `[utils.fs]` - Added several helpers include `fs.Tmp` for creation and cleanup of temporary directory and file.

**Refactoring:**

* *Too many to reference*

**Incompatible:**

* `[core]` Replace Interfaces with ABC Base Classes
  * [Issue #192](https://github.com/datafolklabs/cement/issues/192)
* `[core.foundation]` Rename `CementApp` to `App`.
* `[core.foundation]` Drop deprecated `App.Meta.override_arguments`
* `[core.foundation]` Remove `App.Meta.plugin_config_dir` and `App.Meta.plugin_config_dirs` in favor of `App.Meta.config_dirs`
  * [Issue #521](https://github.com/datafolklabs/cement/issues/521)
* `[core.founcation]` Rename `App.Meta.plugin_bootstrap` as `App.Meta.plugin_module`
  * [Issue #523](https://github.com/datafolklabs/cement/issues/523)
* `[core.handler]` Rename `CementBaseHandler` to `Handler`
* `[core.handler]` Drop deprecated backend globals
* `[core.hook]` Drop deprecated backend globals
* `[core.controller]` Drop `CementBaseController`
* `[ext.logging]` Drop deprecated `warn` facility (use `warning`)
* `[ext.argcomplete]` Drop ArgComplete Extension
* `[ext.reload_config]` Drop Reload Config Extension
* `[ext.configobj]` Drop ConfigObj Extension
* `[ext.json]` Disable `overridable` option by default
* `[ext.yaml]` Disable `overridable` option by default
* `[ext.json_configobj]` Drop JSON ConfigObj Extension
* `[ext.yaml_configobj]` Drop YAML ConfigObj Extension
* `[ext.handlebars]` Drop Handlebars Extension
* `[ext.genshi]` Drop Genshi Extension
* `[ext.argparse]` `ArgparseController.Meta.default_func` is now `_default`, and will print help info and exit.  Can now set this to `None` as well to pass/exit.
  * [Issue #426](https://github.com/datafolklabs/cement/issues/426)
* `[ext.plugin]` All plugin configuration sections must start with `plugin.`.

  &#x20; For example, `[plugin.myplugin]`.
* `[core.foundation]` Renamed `App.Meta.config_extension` to `App.Meta.config_file_suffix`
  * [Issue #445](https://github.com/datafolklabs/cement/issues/445)
* `[core.foundation]` Drop `App.Meta.arguments_override_config`
  * [Issue #493](https://github.com/datafolklabs/cement/issues/493)

**Deprecation:**

* *Everything with deprecation notices in Cement < 3*


# Deprecations

## Enabling Deprecation Warnings

Deprecation warnings are handled by the same warning system as Python using the `warnings` library. To enable warning, set the [`PYTHONWARNINGS`](https://docs.python.org/3/using/cmdline.html#envvar-PYTHONWARNINGS) environment variable.

```
export PYTHONWARNINGS=once
```

{% hint style="info" %}
Python warnings should always be enabled for unit tests. Pytest, the default testing framework for Cement generated projects, enables this by default.
{% endhint %}

## Cement v3.0.16

### 3.0.16-1

`SMTPMailHandler.send()` returning bool is deprecated. It will return the smtplib senderrs dict in Cement v3.2.0

## Cement v3.0.10

### 3.0.10-1

The logging facility `FATAL` is being deprecated in favor of `CRITICAL`. This follows the standard library upstream:

* <https://docs.python.org/3/library/logging.html#logging-levels>

Though the FATAL facility [may never be fully removed](https://bugs.python.org/issue40836) upstream, it makes sense to deprecate it in Cement.

{% hint style="warning" %}
Support for the `FATAL` facility, and `app.log.fatal()` may be removed any time in or after Cement v3.2.0.
{% endhint %}

Developers should modify their apps to use critical:

```python
app.log.set_level('CRITICAL')
app.log.critical('Some log message')
```

##

## Cement v3.0.8

### 3.0.8-1

The environment variable `CEMENT_FRAMEWORK_LOGGING` is being deprecated in favor of [`CEMENT_LOG`](/environment-variables#cement_log).

**Related:**

* <https://github.com/datafolklabs/cement/issues/638>

**Usage:**

```
export CEMENT_LOG=1

myapp {command, options, etc}
```

Setting `CEMENT_LOG=1` will set `App.Meta.framework_logging = True`.

{% hint style="warning" %}
Support for `CEMENT_FRAMEWORK_LOGGING` will be removed in Cement v3.2.0.
{% endhint %}

### 3.0.8-2

In Cement v3.0.x, the default for [`App.Meta.framework_logging`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.framework_logging) is `True`, however framework logging is only triggered if the `--debug` option is passed at the command-line. The `--debug` option was previously hard-coded, but is now configurable and therefore should no longer be used to toggle framework logging. &#x20;

In Cement 3.2.0, the logic of `App.Meta.framework_logging` will be repurposed, or removed.  The plan, currently, is that `--debug` will only toggle the logging level and `App.Meta.debug` but not toggle Cement framework logging. One thought is that `App.Meta.framework_logging` could trigger framework/extensions to use the App logger, once it is available (instead of MinimalLogger everywhere).&#x20;

As of 3.0.8, you can use `CEMENT_LOG=1` (environment variable) instead of `--debug` for the same functionality.

FIXME: Exact details to be determined.

Related:

* <https://github.com/datafolklabs/cement/issues/612>
* <https://github.com/datafolklabs/cement/issues/613>


# Getting Started


# Installation

Guide on the initial installation and configuration of Cement.

## Via PIP/PyPi

Stable versions are available via PyPi:

```
$ pip install cement
```

Development versions are available via Github:

```
$ git clone git://github.com/datafolklabs/cement.git
​
$ cd cement/

​$ pdm install
```

## Via Docker

Cement is also available via Docker Hub:

```
$ docker run -it datafolklabs/cement:3.0 --help
```


# Developer Tools

## Introduction

Cement ships with a CLI utility that includes tools and helpers for application developement. It is in-itself an application Built on Cement™, and can serve as a working example of some of the key features of the framework.

Install additional dependencies:

```
$ pip install cement[cli]
```

See:&#x20;

`$ cement --help`

The Cement CLI uses the builtin [Generate Extension](/extensions/generate) in order to easily create new projects, extensions, plugins, or scripts.

See:&#x20;

`$ cement generate --help`

## Creating Your First Project Built on Cement™

Using the Cement Developer Tools CLI, you can quickly generate a new project:

*Note: Press* `<ENTER>` *in order to take the default values for* `myapp`*:*

```
$ cement generate project ./myapp
INFO: Generating cement project in ./myapp
App Label [myapp]:
App Name [My Application]:
App Class Name [MyApp]:
App Description [MyApp Does Amazing Things!]:
Creator Name [John Doe]:
Creator Email [john.doe@example.com]:
Project URL [https://github.com/johndoe/myapp/]:
License [unlicensed]:
```

We have just generated a new project in the directory `./myapp`.  The included `README.md` includes general information that is built-in to your new project out-of-the box including how to setup a development environment, run tests, push packages to PyPi, and deploy via Docker.

## Customizing Templates

The [Generate Extension](/extensions/generate) reads templates from any template directory paths, therefore adding your own templates to Cement is as simple as adding a template directory to Cement's configuration file, cloning a builtin template, and then generating from your own templates using the same utility.

Add the following to `~/.cement.yml`:

```
cement:
    template_dir: ~/templates
```

Then clone an existing template:

```
$ cement generate project \
    --clone ~/templates/generate/my-template
```

Your template is now part of Cement!  Customize it to your liking, and use it in the same way as the builtin templates:

```
$ cement generate --help
usage: cement generate [-h]
                       {project,script,plugin,extension,my-template}
                       ...

optional arguments:
  -h, --help            show this help message and exit

sub-commands:
  {project,script,plugin,extension,my-template}
    project             generate project from template
    script              generate script from template
    plugin              generate plugin from template
    extension           generate extension from template
    my-template         generate my-template from template
    
```


# Framework Overview

An in-depth overview of the key features of the framework that all developers should be familiar with.

This section is intended to give a brief overview of some of the most commonly used core features of Cement. Please do not be discouraged if you don't "get it" right away. Please also do not think, "is this it?". This is not intended to be an exhaustive end-all-be-all coverage of every feature of the framework.

Some assumptions are being made here. Primarily, we assume that you've used and are familiar with Python. The overview is intended to give a high level look at using Cement. Please dive deeper into the individual sections after the overview in order to gain a better understanding of each component.

## The Application Object

The core of your project starts with the Cement `App` object, which we will refer to throughout this documentation in several ways:

* `App` - The uninstantiated Cement `App` base class
* `MyApp` - The uninstatiated/sub-classed Cement application you are creating
* `app` - The instantiated application object

Technically, Cement `App` can be used direcly (as in the example), however in practice you will almost always sub-class `App` in order to configure it for your needs (I.e. `MyApp`).

{% tabs %}
{% tab title="Using App Directly" %}

```python
from cement import App

with App('myapp') as app:
    app.run()
```

{% endtab %}

{% tab title="Subclassing App" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'

with MyApp() as app:
    app.run()
```

{% endtab %}

{% tab title="Usage" %}

```
$ python myapp.py --help
usage: myapp [-h] [--debug] [--quiet]

optional arguments:
  -h, --help  show this help message and exit
  --debug     toggle debug output
  --quiet     suppress all output
```

{% endtab %}
{% endtabs %}

## MetaMixin

Cement uses `MetaMixin` classes everywhere, which allows the framework to define default functionality but also provides an easy mechanism for developers to override and customize.

This is implemented by declaring a `Meta` class, under your application and/or other Cement Handler classes.

Ex: Defining Meta Classes

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['json']
```

All Meta-options can also be overridden by any `**kwargs` that are passed to the parent class that is being instantiated.

Ex: Passing meta options via `**kwargs`:

```python
App('myapp', config_defaults={'foo': 'bar'})
```

Nearly every Cement class has an associated `Meta` class, which we often refer to as `App.Meta`, `SomeHandlerClass.Meta`, etc. The instantiated object is refered to in code as `app._meta`, `some_handler._meta`, etc.

## Interfaces and Handlers

All aspects of the framework are broken up into interfaces, and handlers. Interfaces **define** some functionality, while handlers **implement** that functionality. Cement defines the following builtin core interfaces:

| Interface                                                                                                                           | Descripton                                                                                                                                     |
| ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| [**Extension**](/core-foundation/extensions-1)                                                                                      | Framework extension loading.                                                                                                                   |
| **​**[**Log**](https://cement.readthedocs.io/en/portland/api/core/log/#cement.core.log.LogHandler)**​**                             | Messaging to console, and/or file via common log facilities (INFO, WARNING, ERROR, FATAL, DEBUG).                                              |
| **​**[**Config**](https://cement.readthedocs.io/en/portland/api/core/config/#cement.core.config.ConfigHandler)**​**                 | Merging of application configuration defaults, configuration files, and environment settings into a single config object.                      |
| **​**[**Mail**](https://cement.readthedocs.io/en/portland/api/core/mail/#cement.core.mail.MailHandler)**​**                         | Remote message sending (email, smtp, etc).                                                                                                     |
| **​**[**Plugin**](https://cement.readthedocs.io/en/portland/api/core/plugin/#cement.core.plugin.PluginHandler)**​**                 | Application plugin loading.                                                                                                                    |
| **​**[**Template**](https://cement.readthedocs.io/en/portland/api/core/template/#cement.core.template.TemplateHandler)**​**         | Rendering of template data (content, files, etc).                                                                                              |
| **​**[**Output**](https://cement.readthedocs.io/en/portland/api/core/output/#cement.core.output.OutputHandler)**​**                 | Rendering of data/content to end-user output (console text from template, JSON, Yaml, etc). Often uses an associated template handler backend. |
| **​**[**Argument**](https://cement.readthedocs.io/en/portland/api/core/arg/#cement.core.arg.ArgumentHandler)**​**                   | Command line argument/option parsing.                                                                                                          |
| **​**[**Controller**](https://cement.readthedocs.io/en/portland/api/core/controller/#cement.core.controller.ControllerHandler)**​** | Command dispatch (sub-commands, arguments, etc)                                                                                                |
| **​**[**Cache**](https://cement.readthedocs.io/en/portland/api/core/cache/#cement.core.cache.CacheHandler)**​**                     | Key/Value data store (memcached, redis, etc)                                                                                                   |

To accompany the above interfaces, Cement also defines and registers default Handlers that implement the required functionality. For example, the builtin configuration handler `ConfigParserConfigHandler`, implements the `config` interface.

{% hint style="info" %}
Handlers are referred to by the interfaces they implement, such as `config.configparser`, `config.json`, `config.yaml`, etc. Application developers can also define their own interfaces, allowing customization by plugins.
{% endhint %}

Developers can override the default functionality by creating their own handlers, or by sub-classing what is provided to alter its implementation. The following example demonstrates how you would sub-class and override an existing handler:

Ex: Overriding Default Framework Handlers

```python
from cement import App
from cement.ext.ext_configparser import ConfigParserConfigHandler


class MyConfigHandler(ConfigParserConfigHandler):
    class Meta:
        label = 'my_config_handler'

    # do something to subclass/re-implement
    # config handler here...


class MyApp(App):
    class Meta:
        label = 'myapp'
        config_handler = 'my_config_handler'
        handlers = [
            MyConfigHandler
        ]
```

**Overriding Via Configuration Files**

The `App.Meta` options define the builtin handlers for all of the above listed core handlers. Whatever the application code defines is the default, however you can also override via the configuration file(s).

For example, imagine that your default `mail_handler` is `smtp` for sending email via your local SMTP server. This is a configuration that might vary on a per-user/environment basis. Via the application configuration, you could override this with an alternative mail handler like `mail_handler = some_other_mail_handler`

Ex: Overriding Via Configuration File

{% tabs %}
{% tab title="\~/.myapp.conf" %}

```
[myapp]

### override App.Meta.mail_handler
mail_handler = my_mail_handler
```

{% endtab %}
{% endtabs %}

## Configuration

Cement supports loading multiple configuration files out-of-the-box. Configurations loaded from files are merged in, overriding the applications default settings (`App.Meta.config_defaults`). The default configuration handler is `ConfigParserConfigHandler`, based on [ConfigParser](https://docs.python.org/3/library/configparser.html) in the standard library, and is instantiated as `app.config`.

Cement looks for configuration files in the most common places by default. For example:

* /etc/myapp/myapp.yml
* \~/.config/myapp/myapp.yml
* \~/.config/myapp/config
* \~/.config/myapp.yml
* \~/.myapp.yml
* \~/.myapp/config

The list of configuration file paths can be customized via the meta option [`App.Meta.config_files`](https://cement.readthedocs.io/en/portland/api/core/foundation/#cement.core.foundation.App.Meta.config_files) as well as their extension (i.e. `.conf`) can also be easily modified with [`App.Meta.config_file_suffix`](https://cement.readthedocs.io/en/portland/api/core/foundation/#cement.core.foundation.App.Meta.config_file_suffix).

The builtin configuration handler `ConfigParserConfigHandler` uses common unix-like config files where `blocks` or `sections` are defined with brackets; `[myapp]`, `[plugin.myplugin]`, `[interface.handler]`, etc.

Additional support for the following file formats is provided via optional extensions:

* [Json](/extensions/json)
* [Yaml](/extensions/yaml)

{% hint style="info" %}
Config handler's provide dropin replacements for the default ConfigParserConfigHandler, and are often based on it. For example, the JsonConfigHandler and YamlConfigHandler classes do little more than support reading alternative file formats. Accessing the config settings in the app is exactly the same.
{% endhint %}

All extensions and application plugins can support customizations loaded from the application configuration files under the section `[interface.handler]`. For example, the `ColorLogHandler` extension reads it's configuration from `[log.colorlog]`.

Ex: Application Configuration Settings

{% tabs %}
{% tab title="myapp.py" %}

```python
from cement import App, init_defaults

defaults = init_defaults('myapp')
defaults['myapp']['foo'] = 'bar'

class MyApp(App):
    class Meta:
        label = 'myapp'
        config_defaults = defaults

with MyApp() as app:
    app.run()
    print("Foo => %s" % app.config.get('myapp', 'foo'))
```

{% endtab %}

{% tab title="\~/.myapp.conf" %}

```
[myapp]
foo = not-bar
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
Foo => not-bar
```

{% endtab %}
{% endtabs %}

**Alternative Configuration Handler Example**

The following is an example of overriding the default config handler with an alternative, drop-in replacement `YamlConfighandler`:

Ex: Alternative Configuration Handler (Yaml):

{% tabs %}
{% tab title="myapp.py" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['yaml']
        config_handler = 'yaml'
        config_file_suffix = '.yml'
```

{% endtab %}

{% tab title="\~/.myapp.yml" %}

```yaml
myapp:
    foo: not-bar
```

{% endtab %}
{% endtabs %}

**Overriding Configuration Settings with Environment Variables**

All configuration settings can be overridden by their associated environment variables. For example `config['myapp']['foo']` is overridable by `$MYAPP_FOO`.

Note that all environment variable configurations are prefixed with the application label, therefore secondary namespaces such as `config['log.logging']['level']` would be overridable by `MYAPP_LOG_LOGGING_LEVEL`.

## Arguments

Argument parsing is based on the standard [Argparse](https://docs.python.org/3/library/argparse.html) library, with the same usage that you're familiar with. The argument handler `ArgparseArgumentHandler` is instantiated as `app.args`, arguments are defined with `app.args.add_argument()`, and parsed arguments are stored as `app.args.parsed_args` (or more conveniently `app.pargs` for easy reference).

Ex: Simple Arguments Defined With Cement App

{% tabs %}
{% tab title="myapp.py" %}

```python
from cement import App

with App('myapp') as app:
    app.args.add_argument('-f', '--foo',
                          help='notorous foo option',
                          dest='foo')
    app.run()

    # do something with parsed arguments
    if app.pargs.foo is not None:
        print("Foo Argument => %s" % app.pargs.foo)
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py --help
usage: myapp [-h] [--debug] [--quiet] [-f FOO]

optional arguments:
  -h, --help         show this help message and exit
  --debug            toggle debug output
  --quiet            suppress all output
  -f FOO, --foo FOO  notorous foo option

$ python myapp.py -f bar
Foo Argument => bar
```

{% endtab %}
{% endtabs %}

**Arguments Defined by Controllers**

The power of the framework comes into play when we start talking about application controllers that streamline the process of mapping arguments and sub-commands to actions/functions as in the example (more on this later).

Ex: Arguments Defined by Controllers

{% tabs %}
{% tab title="myapp.py" %}

```python
from cement import App, Controller, ex


class Base(Controller):
    class Meta:
        label = 'base'

        arguments = [
            # list of tuples in the format `( [], {} )`
            ( [ '-f', '--foo' ],
              { 'help' : 'notorious foo option',
                'dest' : 'foo' } ),
        ]

    @ex(hide=True)
    def _default(self):
        print('Inside BaseController._default()')

        # do something with parsed arguments
        if self.app.pargs.foo is not None:
            print("Foo Argument => %s" % self.app.pargs.foo)


class MyApp(App):
    class Meta:
        label = 'myapp'
        handlers = [Base]


with MyApp() as app:
    app.run()
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py --help
usage: myapp [-h] [--debug] [--quiet] [-f FOO]

optional arguments:
  -h, --help         show this help message and exit
  --debug            toggle debug output
  --quiet            suppress all output
  -f FOO, --foo FOO  notorous foo option

$ python myapp.py -f bar
Foo Argument => bar
```

{% endtab %}
{% endtabs %}

## Logging

Logging is based on the standard [Logging](https://docs.python.org/3/library/logging.html) library, with the same usage you're familiar with. The logging facility is customizable via the `[log.logging]` section of an applications configuration:

* `level` - The level at which to start logging (`INFO`, `WARNING`, `ERROR`,

  `FATAL`, `DEBUG`, etc).
* `file` (*path*) - File path to log to.
* `to_console` (*bool*) - Whether or not to log to console.
* `rotate` (*bool*) - Whether or not to rotate the log file when it hits

  `max_bytes`
* `max_bytes` (*int*) - Maximum file size in bytes before file gets rotated
* `max_files` (*int*) - Maximum number of log files to keep after rotating

Cement also includes the following optional extensions that provide drop-in replacements for the default log handler:

* [ColorlogHandler](/extensions/colorlog) - Provides colorized log output via the [Colorlog](https://github.com/borntyping/python-colorlog) library.

Ex: Logging Example

{% tabs %}
{% tab title="myapp.py" %}

```python
from cement import App

with App('myapp') as app:
    app.run()

    # log messages to console and file
    app.log.info('this is an info message')
    app.log.warning('this is an warning message')
    app.log.error('this is an error message')
    app.log.fatal('this is an fatal message')
    app.log.debug('this is an debug message')
```

{% endtab %}

{% tab title="\~/.myapp.conf" %}

```
[myapp]
log_handler = logging

[log.logging]
to_console = true
file = /path/to/myapp.log
level = warning
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
INFO: this is an info message
WARNING: this is an warning message
ERROR: this is an error message
CRITICAL: this is an fatal message
```

{% endtab %}
{% endtabs %}

## Output

By default, Cement does not define any output handlers. Just like any other app, you are free to `print()` to console all you like or use the builtin logging facility. That said, more complex applications will benefit greatly by separating the output from the logic. Think of output handling as the `view` in a traditional [MVC Framework](https://en.wikipedia.org/wiki/Model-view-controller).

Cement ships with several types of extensions that produce output in different forms, including the following:

* Text Rendered From Template Files
* Programatic Structures (JSON, Yaml, etc)
* Tabulated (like MySQL, etc)
* Etc

The following output handlers ship with Cement:

* [Json](/extensions/json) - Produces JSON output from dicts
* [Yaml](/extensions/yaml) - Produces Yaml output from dicts
* [Mustache](/extensions/mustache) - Produces text output rendered from [Mustache](http://mustache.github.io/) templates
* [Handlebars](/getting-started/framework-overview) - Produces text output rendered from [Handlebars](https://github.com/wbond/pybars3) templates
* [Jinja2](/extensions/jinja2) - Produces text output rendered from [Jinja2](http://jinja.pocoo.org/) templates
* [Tabulated](/extensions/tabulate) - Produces tabulated text output rendered via the [Tabulate](https://pypi.python.org/pypi/tabulate) library.

**Multiple Output Handler Support**

One of the unique features of Cement is that you can build your application to support multiple output handlers and formats. Output handlers have a special attribute that *optionally* allows them to be exposed via the CLI option `-o` (configurable via [`Handler.Meta.overridable`](http://cement.readthedocs.io/en/3.0/api/core/handler/#cement.core.handler.Handler.Meta.overridable) and [`App.Meta.core_handler_override_options`](https://cement.readthedocs.io/en/portland/api/core/foundation/#cement.core.foundation.App.Meta.core_handler_override_options)). Therefore, you might have default text based output rendered from Mustache templates, but optionally output programatic structures **from the same code** when necessary (i.e.`$ myapp -o json`).

Ex: Mixed Template/JSON Output Example

{% tabs %}
{% tab title="myapp.py" %}

```python
from cement import App, init_defaults

META = init_defaults('output.json')
META['output.json']['overridable'] = True

class MyApp(App):
    class Meta:
        label = 'myapp'

        ### override default handler meta options
        meta_defaults = META

        ### add optional extensions
        extensions = ['json', 'mustache']

        ### set the default output handler
        output_handler = 'mustache'

        ### external template directory
        template_dir = '/path/to/templates'

        ### internal template module (shipped with app code)
        template_module = 'myapp.templates'


with MyApp() as app:
    app.run()

    ### create some data
    data = {
        'foo' : 'bar',
    }

    ### render data using mustache template (by default)
    app.render(data, 'example.m')
```

{% endtab %}

{% tab title="templates/example.m" %}

```
The value of foo={{foo}}.
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py --help
usage: myapp [-h] [--debug] [--quiet] [-o {json}]

optional arguments:
  -h, --help  show this help message and exit
  --debug     toggle debug output
  --quiet     suppress all output
  -o {json}   output handler


$ python myapp.py
The value of foo=bar


$ python myapp.py -o json
{"foo": "bar"}
```

{% endtab %}
{% endtabs %}

## Controllers

Controllers provide a common means of organizing application logic into relevant chunks of code, as well as the ability for plugins and extensions to extend an applications capabilities. It is the `Controller` piece of the traditional [MVC Framework](https://en.wikipedia.org/wiki/Model-view-controller).

The first controller is called `base`, and if registered will take over runtime control when `app.run()` is called. What this means is, instead of Cement calling `app.args.parse_arguments()` directly, the [runtime dispatch](/terminology#runtime-dispatch) is handed over to the `base` controller, that is then responsible for parsing and handling arguments.

The most notable action of runtime dispatch is mapping arguments and sub-commands to their respective controllers and functions. For example, the default action when running `$ myapp` without any arguments or sub-commands is to execute the `Base._default()` function.

Ex: Application Base Controller

{% tabs %}
{% tab title="myapp.py" %}

```python
from cement import App, Controller, ex


class Base(Controller):
    class Meta:
        label = 'base'

        arguments = [
            # list of tuples in the format `( [], {} )`
            ( [ '-a' ],
              { 'help' : 'example a option',
                'dest' : 'a' } ),
        ]

    def _default(self):
        print('Inside Base._default()')
        if self.app.pargs.a:
            print('Received Option: -a')

    @ex(
        help='sub-command under base controller',
        arguments=[
            ( [ '-b' ],
              { 'help' : 'cmd1 b option' } ),
        ]
    )
    def cmd1(self):
        print('Inside Base.cmd1()')
        if self.app.pargs.b:
            print('Recieved Option: -b')


class MyApp(App):
    class Meta:
        label = 'myapp'
        handlers = [
            Base,
        ]


with MyApp() as app:
    app.run()
```

{% endtab %}

{% tab title="cli" %}

```
### help output shows base namespace arguments and sub-commands

$ python myapp.py --help
usage: myapp [-h] [--debug] [--quiet] [-a A] {cmd1} ...

optional arguments:
  -h, --help  show this help message and exit
  --debug     toggle debug output
  --quiet     suppress all output
  -a A        example a option

sub-commands:
  {cmd1}
    cmd1      sub-command under base controller


$ python myapp.py -a foo
Inside Base._default()
Received Option: -a


### sub-commands support their own arguments

$ python myapp.py cmd1 --help
usage: myapp cmd1 [-h] [-b B]

optional arguments:
  -h, --help  show this help message and exit
  -b B        cmd1 b option


$ python myapp.py cmd1 -b foo
Inside Base.cmd1()
Recieved Option: -b
```

{% endtab %}
{% endtabs %}

**Nested / Embedded Controllers**

Cement supports two types of [controller stacking](/terminology#controller-stacking):

* **nested** - The arguments and commands are nested under a sub-parser whose label is that of the controller.  For example, a nested controller with a label of `my-nested-controller` would be called as `$ myapp my-nested-controller sub-command`.
* **embedded** - The arguments and commands are embedded within it's parent controller, therefore appearing as if they were defined by the parent itself.  A sub-command under an embedded controller would be called as `$ myapp sub-command`.

Controllers can be stacked on other controllers as many levels deep as necessary. An `embedded` controller can be stacked on top of a `nested` controller, and vice versa. There is little, if any, limitation.

**Controller Arguments vs Command Arguments**

Both Controllers and their sub-commands can have arguments defined. Think of controllers as the primary namespace. It's arguments should be globally relevant within that namespace. A sub-command within the namespace can have it's own arguments, but are only relevant to that sub-command.

Ex: `$ myapp -a my-controller -b my-sub-command -c`

In the above example, `-a` is relevant to the global scope of the entire application because it is defined on the `base` controller. Option `-b` is relevant to the scope of `my-controller` and all sub-commands under it. Finally, `-c` is only relevant to the `my-sub-command` and has no use elsewhere.

**Exposing Sub-Commands**

By default, no commands are exposed to the CLI except that a `_default()` function will be called if no sub-command is passed (configurable by `Controller.Meta.default_func`).

To expose a function as a sub-command, you must decorate it with `@ex()`. It's usage is simple, and supports the following parameters:

* `hide` (*bool*) - Whether or not to display in `--help` output.
* `arguments` (*list*) - Argument list of tuples in the format `( [], {} )`, that are passed to `Argparse.add_argument(*args, **kwargs)`.
* `**kwargs` - Additional keyword arguments are passed directly to Argparse when creating the sub-parser for this command.

{% hint style="info" %}
The term `ex` is short for `expose`, and allows for shorter reference and also four character indentation/alignment with functions to be easier on the eyes.
{% endhint %}

## Framework Extensions

Cement's [Interfaces and Handlers](/core-foundation/interfaces-and-handlers) system makes extending the framework easy, and limitless. Cement ships with dozens of extensions that either alter existing functionality, or add to it. For example, the default logging facility provides basic logging capabilities, however with a single line of code an application can instead use the [Colorlog](/extensions/colorlog) extension to enable colorized console logging.

The following example provides a quick look at using the [Alarm](/extensions/alarm) extension to handle application timeouts of long running operations

Ex: Using Framework Extensions:

{% tabs %}
{% tab title="myapp.py" %}

```python
from time import sleep
from cement import App


class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['alarm']


with MyApp() as app:
    app.run()

    ### set an alarm for max allowed run time
    app.alarm.set(3, "The operation timed out after 3 seconds!")

    ### do something that takes time to operate
    sleep(5)

    ### stop the alarm if it ran within the time frame
    app.alarm.stop()
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
ERROR: The operation timed out after 3 seconds!
Traceback (most recent call last):
  File "myapp.py", line 20, in <module>
    sleep(5)
  File "cement/core/foundation.py", line 123, in cement_signal_handler
    raise exc.CaughtSignal(signum, frame)
cement.core.exc.CaughtSignal: Caught signal 14
```

{% endtab %}
{% endtabs %}

See the [Extensions Documentation](/core-foundation/extensions-1) to learn more about the extended capabilities of the framework.

## Application Plugins

Cement provides an interface that automatically handles the management, configuration, and loading of Application Plugins. A Plugin is essentially the same as a Framework Extension, but is application specific where extensions are agnostic (can be used by any application).

A plugin can be anything, and provide any kind of functionality from defining runtime hooks, to extending an applications capabilities by adding nested/embedded controllers. The only thing that a plugin must provide is a `load()` function that is called when the plugin is imported.

Ex: Basic Application

{% tabs %}
{% tab title="myapp.py" %}

```python
from cement import App, Controller, ex


class Base(Controller):
    class Meta:
        label = 'base'


class MyApp(App):
    class Meta:
        label = 'myapp'
        handlers = [
            Base,
        ]


with MyApp() as app:
    app.run()
```

{% endtab %}

{% tab title="cli" %}

```
$ python test.py --help
usage: myapp [-h] [--debug] [--quiet] {} ...

optional arguments:
  -h, --help  show this help message and exit
  --debug     toggle debug output
  --quiet     suppress all output

sub-commands:
  {}
```

{% endtab %}
{% endtabs %}

Using the same application, we can create a plugin to extend functionality:

Ex: Application Plugin

{% tabs %}
{% tab title="myplugin.py" %}

```python
from cement import Controller, ex


class MyPlugin(Controller):
    class Meta:
        label = 'myplugin'
        stacked_on = 'base'
        stacked_type = 'embedded'

    @ex()
    def cmd1(self):
        print('Inside MyPlugin.cmd1()')


def load(app):
    app.handler.register(MyPlugin)
```

{% endtab %}

{% tab title="\~/.myapp.conf" %}

```
[myapp]
plugin_dir = /path/to/myapp/plugins

[plugin.myplugin]
enabled = true
```

{% endtab %}

{% tab title="cli " %}

```
$ python myapp.py --help
usage: myapp [-h] [--debug] [--quiet] {cmd1} ...

optional arguments:
  -h, --help  show this help message and exit
  --debug     toggle debug output
  --quiet     suppress all output

sub-commands:
  {cmd1}


$ python myapp.py cmd1
Inside MyPlugin.cmd1()
```

{% endtab %}
{% endtabs %}

## Hooks

Hooks provide developers the ability to tie into the framework, and applications without direct access to the runtime. For example, a plugin might need to execute some code after arguments have been parsed, but before controller sub-commands are dispatched. As a plugin developer, you don't have direct access to the applications runtime code but you can still tie into it with the builtin `post_argument_parsing` hook.

Cement defines several hooks that tie in to specific points throughout the application life cycle, however application developers can also define their own hooks allowing others to tie elsewhere, when needed.

Ex: Executing Code Via Hooks

{% tabs %}
{% tab title="myapp.py" %}

```python
from cement import App


def my_example_hook(app):
    print('Inside my_example_hook()')


class MyApp(App):
    class Meta:
        label = 'myapp'
        hooks = [
            ('post_argument_parsing', my_example_hook),
        ]


with MyApp() as app:
    app.run()
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
Inside my_example_hook()
```

{% endtab %}
{% endtabs %}


# Beginner Tutorial


# Part 1: Creating Your First Project

## Introduction

Throughout this tutorial we will be building a task management application called `todo`. We will begin with a barebones template using the `cement generate` tool, and build up from there to cover as much of the core features of the framework as possible.

Our application will include the following features:

* Ability to create, update, and delete task items
* List and display tasks via [Jinja2](/extensions/jinja2) templates
* Persist data using [TinyDB](http://tinydb.readthedocs.io/en/latest/intro.html)
* Send an email message when tasks are complete

A [video walk-thru](https://builtoncement.com/assets/video/beginner-tutorial.mp4) of the tutorial is also available.

## Generating a New Project Repository

Cement includes a [developer utility](/getting-started/developer-tools) called `cement` that includes tools to make our lives easier. This was introduced in Cement 3, and will continue to grow as feature requests are made for new and improved ways of streamlining the development process.

Create a new project with the following command and parameters:

```
$ cement generate project ./todo
INFO: Generating cement project in ./todo
App Label [myapp]: todo
App Name [My Application]: My TODO Application
App Class Name [MyApp]: Todo
App Description [MyApp Does Amazing Things!]: A Simple TODO Application
Creator Name [John Doe]: Your Name
Creator Email [john.doe@example.com]: you@yourdomain.com
Project URL [https://github.com/johndoe/myapp/]: https://github.com/yourname/todo/
License [unlicensed]:
```

## Exploring The TODO Project

The following covers the primary components included with your new project. First, take a look at the generated directory:

```
.
├── CHANGELOG.md
├── Dockerfile
├── LICENSE.md
├── MANIFEST.in
├── Makefile
├── README.md
├── config
│   └── todo.yml.example
├── docs
├── requirements-dev.txt
├── requirements.txt
├── setup.cfg
├── setup.py
├── tests
│   ├── conftest.py
│   └── test_main.py
└── todo
    ├── controllers
    │   └── base.py
    ├── core
    │   ├── exc.py
    │   └── version.py
    ├── ext
    ├── main.py
    ├── plugins
    └── templates
        └── command1.jinja2

9 directories, 24 files
```

This looks like a lot, however there is a lot of placeholders here for best practice or recommended design. Keep in mind, a Cement application can be as simple as a single file script... however we know that our TODO application will be disrupting the industry of task management, therefore we want to start things on the right track.

Let's break this down into more manageable pieces:

**Common Project Files**

```
├── CHANGELOG.md
├── LICENSE.md
├── README.md
```

These files should look familiar as they are common in most projects. The `README.md` is populated with some starter info to help get more familiar with the layout and navigation of the project. You should read the `README.md` now.

**Common Python Packaging Files**

```
├── MANIFEST.in
├── requirements-dev.txt
├── requirements.txt
├── setup.cfg
├── setup.py
```

These files should look familiar to anyone who has packaged and distributed a Python project before, and are required for proper installation, setup, and distribution. Note that the `requirements.txt` lists dependencies that are strictly required for deployment (production), where the additional `requirements-dev.txt` includes additional dependencies that are only required for development (running tests, building documentation, etc).

**Miscellaneous Development Files**

```
├── Dockerfile
├── Makefile
```

The included `Dockerfile` gives you a working Docker image out-of-the box, while the `Makefile` includes several helpers for common development tasks such as creating a virtualenv, running tests, building docker, etc.

**Default Configuration, Documentation, and Tests**

```
├── config
│   └── todo.yml.example
├── docs
├── tests
│   ├── conftest.py
│   └── test_main.py
```

A good application has excellent documentation and testing, along with example configuration files of the applications settings (and their defaults). As configuration defaults are added (or modified) in the application, the `config/todo.yml.example` should be updated to reflect them.

**Our Application Module**

```
└── todo
    ├── controllers
    │   └── base.py
    ├── core
    │   ├── exc.py
    │   └── version.py
    ├── ext
    ├── main.py
    ├── plugins
    └── templates
        └── command1.jinja2
```

Finally, our code lives in a python module called `todo`, with what should be an obvious breakdown of submodules that clearly separate code into relevant and organized buckets. Take a moment to briefly review all of the files provided in the generated project repository.

Again, note that a Cement project does not need to be organized this way but is a solid starting point to streamline development. If you aren't entirely happy with the layout and organization of the generated projects you can always [create your own templates to start from](/getting-started/developer-tools#customizing-templates).

## Setting up Our Development Environment

Our generated project includes a `Makefile` with several helpers to streamline the development process. You can use these helpers, add your own, or do away with it and follow any other development process you are more familiar with.

First we will setup our VirtualENV:

```
$ make virtualenv

$ source env/bin/activate

|> todo <| $
```

This runs common commands to create our virtual environment in `./env/`, and then runs `pip` to install our dependencies. We activate the environment, and are ready to run our TODO application:

```
|> todo <| $ todo --help
usage: todo [-h] [-d] [-q] [-v]
            {command1} ...

A Simple TODO Application

optional arguments:
  -h, --help            show this help message and exit
  -d, --debug           full application debug mode
  -q, --quiet           suppress all console output
  -v, --version         show program's version number and exit

sub-commands:
  {command1}
    command1            example sub command1

Usage: todo command1 --foo bar
```

Look at that! Let's play around with some of the pre-built features:

```
### display version information

$ todo --version
A Simple TODO Application 0.0.1.dev20180730022818
Cement Framework 3.0.0 
Python 3.7.0
Platform Darwin-17.7.0-x86_64-i386-64bit

### display sub-command help

$ todo command1 --help
usage: todo command1 [-h] [-f FOO]

optional arguments:
  -h, --help         show this help message and exit
  -f FOO, --foo FOO  notorious foo option

### execute the example command1 sub-command

$ todo command1 -f bar
Example Template (templates/command1.jinja2)
Foo => bar
```

## Conclusion

And that completes Part 1. In the next section we will add the functionality of managing task items, storing data in a database, and sending email messages when completing tasks.


# Part 2: Adding Features

Now that we have a working development environment and have become familiar with running our `todo` app, we can build in our initial feature set to manage task items.

## Persistent Storage

Before we can create anything, we need some way to store it.  For this project, we've chosen [TinyDB](http://tinydb.readthedocs.io/en/latest/), a light-weight key-value database that stores data on disk in a single JSON file.

Let's begin by adding the dependency to our `requirements.txt` file, and installing it to our virtualenv:

{% tabs %}
{% tab title="Add TinyDB Dependency" %}
Add the following to the bottom of the pip `requirements.txt` file:

```
tinydb
```

Install the new requirements with `pip`:

```
$ pip install -r requirements.txt
...
Successfully installed tinydb-3.10.0
```

{% endtab %}
{% endtabs %}

With our dependency installed, we need to add it to our application.  The primary things we will cover here are:

* Configuration settings for where we will store the `db.json` file on disk
* Using framework hooks to run code at a specific point in our runtime
* Extending our `app` with a `db` object we will use to integrate and access the TinyDB functionality in our application

{% tabs %}
{% tab title="Add Configuration Defaults" %}
Find and modify the following section of `todo/main.py` in order to define a default configuration for our database file called `db_file`:

```python
# configuration defaults
CONFIG = init_defaults('todo')
CONFIG['todo']['db_file'] = '~/.todo/db.json'
```

To be kind to our users, we will also want to add this default setting to our example configuration file `config/todo.yml.example`.  Modify the file to include the following:

```yaml
---
todo:

### Database file path
# db_file: ~/.todo/db.json
```

{% endtab %}
{% endtabs %}

We want to extend our application with a re-usable `db` object that can be used throughout our code.  There are many ways we could do this, however here we are going to use a [framework hook](/core-foundation/hooks).

{% tabs %}
{% tab title="Add DB Object Code" %}
Add the following to the top of the `todo/main.py` file:

```python
import os
from tinydb import TinyDB
from cement.utils import fs

def extend_tinydb(app):
    app.log.info('extending todo application with tinydb')
    db_file = app.config.get('todo', 'db_file')
    
    # ensure that we expand the full path
    db_file = fs.abspath(db_file)
    app.log.info('tinydb database file is: %s' % db_file)
    
    # ensure our parent directory exists
    db_dir = os.path.dirname(db_file)
    if not os.path.exists(db_dir):
        os.makedirs(db_dir)

    app.extend('db', TinyDB(db_file))
```

We've created a function to extend our application to include an `app.db` object, however in order for it to take affect we need to register the function as a hook with the framework.  Add the following `hooks` meta option to our Todo app in `todo/main.py`:

```python
class Todo(App):
    class Meta:
        hooks = [
            ('post_setup', extend_tinydb),
        ]
```

Now, when we run `todo` again you will see that our hook is executed (via the `info` logs):

```
$ todo --help
INFO: extending todo application with tinydb
INFO: tinydb database file is: /Users/derks/.todo/db.json
...
```

And we can see that the database was created:

```
$ cat ~/.todo/db.json
{"_default": {}}
```

{% endtab %}
{% endtabs %}

## Controllers and Sub-Commands

In order to work with todo items we need to map out commands with our app.  We could do this with the existing `Base` controller, however to keep code clean and organized we want to create an new controller called `Items`. &#x20;

At this point, we have a decision to make regarding [controller stacking](/terminology#controller-stacking).  Do we want our controllers commands to appear **embedded** under the primary applications namespace (ex: `todo my-command`) or do we want a separate **nested** namespace (ex: `todo items my-command`).  As our application is still small, we will opt to embed our controllers commands under the primary namespace (to keep our commands and examples shorter).

{% tabs %}
{% tab title="Add Items Controller Code" %}
Add the following stubs to `todo/controllers/items.py` as a placeholder for our sub-commands:

```python
from cement import Controller, ex


class Items(Controller):
    class Meta:
        label = 'items'
        stacked_type = 'embedded'
        stacked_on = 'base'
    
    @ex(help='list items')
    def list(self):
        pass
        
    @ex(help='create new item')
    def create(self):
        pass
        
    @ex(help='update an existing item')
    def update(self):
        pass
    
    @ex(help='delete an item')
    def delete(self):
        pass
    
    @ex(help='complete an item')
    def complete(self):
        pass
        
```

{% endtab %}
{% endtabs %}

We've created the controller code, however for it to take affect we need to register it with our application.

{% tabs %}
{% tab title="Register Controller with App" %}
Add/modify the following in `todo/main.py`:

```python
from .controllers.items import Items

class Todo(App):
    class Meta:
        # ...
        handlers = [
            Base,
            Items,
        ]
```

With our new controller registered, lets see it in action:

```
$ todo --help
INFO: extending todo application with tinydb
INFO: tinydb database file is: /Users/derks/.todo/db.json
usage: todo [-h] [-d] [-q] [-v]
            {complete,create,delete,update} ...

A Simple TODO Application

optional arguments:
  -h, --help            show this help message and exit
  -d, --debug           full application debug mode
  -q, --quiet           suppress all console output
  -v, --version         show program's version number and exit

sub-commands:
  {complete,create,delete,update}
    complete            complete an item
    create              create new item
    delete              delete an item
    update              update an existing item

Usage: todo command1 --foo bar
```

{% endtab %}
{% endtabs %}

## Feature Functionality

We've stubbed out our `Items` controller and sub-commands, so lets add the actual code that will support each of these features:

### Create Items

{% tabs %}
{% tab title="Add Create Items Code" %}
Add/modify the following in `todo/controllers/items.py`:

{% code title="todo/controllers/items.py" %}

```python
from time import strftime

class Items(Controller):
    # ...
    
    @ex(
        help='create an item',
        arguments=[
            ( ['item_text'],
              {'help': 'todo item text',
               'action': 'store' } )
        ],
    )
    def create(self):
        text = self.app.pargs.item_text
        now = strftime("%Y-%m-%d %H:%M:%S")
        self.app.log.info('creating todo item: %s' % text)

        item = {
            'timestamp': now,
            'state': 'pending',
            'text': text,
        }

        self.app.db.insert(item)
```

{% endcode %}

We've now built out the functionality to create items in our database, that will include the `text`, a `state` (pending/complete), and also the `timestamp` of when it was created/updated. Notice that we've added arguments to the sub-command function, and not the controller because the `item_text` argument is only relevant to the `create` action, and not the application or controller namespace as a whole.

&#x20;Let's try it out:

```
$ todo create "Call Saul"
INFO: creating todo item: Call Saul

$ todo create "Go to Car Wash"
INFO: creating todo item: Go to Car Wash

$ todo create "Meet with Jessie About a Thing"
INFO: creating todo item: Meet with Jessie About a Thing
```

{% endtab %}
{% endtabs %}

### List Items

We've created an item, so now we need to be able to list them.  First, let's take a look at our database:

```
$ cat ~/.todo/db.json | python -m json.tool
{
    "_default": {
        "1": {
            "timestamp": "2018-07-30 15:11:53",
            "state": "pending",
            "text": "Call Saul"
        },
        "2": {
            "timestamp": "2018-07-30 15:12:07",
            "state": "pending",
            "text": "Go to Car Wash"
        },
        "3": {
            "timestamp": "2018-07-30 15:12:54",
            "state": "pending",
            "text": "Meet with Jessie About a Thing"
        }
    }
}
```

We can see that TinyDB automatically generates database IDs, so we will want to display that when listing our items so that we can easily update/delete/complete by ID later.

{% tabs %}
{% tab title="Add List Items Code" %}
Add/modify the following in `todo/controllers/items.py`:

{% code title="todo/controllers/items.py" %}

```python
class Items(Controller):
    # ...
    
    @ex(help='list items')
    def list(self):
        data = {}
        data['items'] = self.app.db.all()
        self.app.render(data, 'items/list.jinja2')
```

{% endcode %}

Here we are pulling all of the items from the database, putting it into a data dictionary, then rendering with the [Jinja2OutputHandler](/extensions/jinja2).  Put the following in the template file `todo/templates/items/list.jinja2`:

{% code title="todo/templates/items/list.jinja2" %}

```
{% for item in items %}
{{ item.doc_id }} [{% if item.state == 'complete' %}X{% else %} {% endif %}] {{ item.text }}
{% endfor %}
```

{% endcode %}

It's a little messy, but that's why we put this in a separate template and not in our code.  We are including the ID so that we can use that for updating/deleting/etc, and also a `[ ]` (checkbox) that will be "checked" when the item's state is `complete`.

Let's have a go:

```
$ todo list
1 [ ] Call Saul
2 [ ] Go to Car Wash
3 [ ] Meet with Jessie About a Thing
```

{% endtab %}
{% endtabs %}

### Update Items

If we've made a typo, or want to change an existing item we need a way to update it. &#x20;

{% tabs %}
{% tab title="Add Update Items Code" %}
Add/modify the following in `todo/controllers/items.py`:

{% code title="todo/controllers/items.py" %}

```python
class Items(Controller):
    # ...

    @ex(
        help='update an existing item',
        arguments=[
            ( ['item_id'],
              {'help': 'todo item database id',
               'action': 'store' } ),
            ( ['--text'],
              {'help': 'todo item text',
               'action': 'store' ,
               'dest': 'item_text' } ),
        ],
    )
    def update(self):
        id = int(self.app.pargs.item_id)
        text = self.app.pargs.item_text
        now = strftime("%Y-%m-%d %H:%M:%S")
        self.app.log.info('updating todo item: %s - %s' % (id, text))

        item = {
            'timestamp': now,
            'text': text,
        }

        self.app.db.update(item, doc_ids=[id])
```

{% endcode %}

Given a TinyDB ID, we can update our item including touching the `timestamp` and modifying the text.  Let's update our todo item:

```
$ todo update 2 --text "Send Skyler to Car Wash"
INFO: updating todo item: 2 - Send Skyler to Car Wash

$ todo list
1 [ ] Call Saul
2 [ ] Send Skyler to Car Wash
3 [ ] Meet with Jessie About a Thing
```

{% endtab %}
{% endtabs %}

### Complete Items

A TODO list is not complete (ah! pun intended) without the ability to check off items that are done. This operation gets a little more interesting as we want to also send an email message when items are completed.

{% tabs %}
{% tab title="Add Complete Items Code" %}
Add/modify the following in `todo/controllers/items.py`:

{% code title="todo/controllers/items.py" %}

```python
class Items(Controller):
    # ...
    
    @ex(
        help='complete an item',
        arguments=[
            ( ['item_id'],
              {'help': 'todo item database id',
              'action': 'store' } ),
        ],
    )
    def complete(self):
        id = int(self.app.pargs.item_id)
        now = strftime("%Y-%m-%d %H:%M:%S")
        item = self.app.db.get(doc_id=id)
        item['timestamp'] = now
        item['state'] = 'complete'

        self.app.log.info('completing todo item: %s - %s' % (id, item['text']))
        self.app.db.update(item, doc_ids=[id])

        ### send an email message
        
        msg = """
        Congratulations! The following item has been completed:

        %s - %s
        """ % (id, item['text'])
        
        self.app.mail.send(msg,
                      subject='TODO Item Complete',
                      to=[self.app.config.get('todo', 'email')],
                      from_addr='noreply@localhost',
                      )
```

{% endcode %}

Add/modify the following in `todo/main.py`:

```python
# configuration defaults
CONFIG = init_defaults('todo')
CONFIG['todo']['email'] = 'you@yourdomain.com'
```

Now let's complete one of our items:

```
$ todo complete 2
INFO: completing todo item id: 2

=============================================================================
DUMMY MAIL MESSAGE
-----------------------------------------------------------------------------

To: you@yourdomain.com
From: noreply@localhost
CC:
BCC:
Subject: TODO Item Complete

---


        Congratulations! The following item has been completed:

        2 - Send Skyler to Car Wash


-----------------------------------------------------------------------------

$ todo list
1 [ ] Call Saul
2 [X] Send Skyler to Car Wash
3 [ ] Meet with Jessie About a Thing
```

{% hint style="info" %}
Notice that the email message was not sent, but rather printed to console.  This is because the default `mail_handler` is set to `dummy`.  You can override this to use the `smtp` mail handler via the applications configuration files (ex:`~/.todo.yml)`
{% endhint %}
{% endtab %}
{% endtabs %}

### Delete Items

Finally, if we just want to get rid of something, we need the ability to delete it:

{% tabs %}
{% tab title="Add Delete Code" %}
Add/modify the following in `todo/controllers/items.py`:

{% code title="todo/controllers/items.py" %}

```python
class Items(Controller):
    # ...
    
    @ex(
        help='delete an item',
        arguments=[
            ( ['item_id'],
              {'help': 'todo item database id',
              'action': 'store' } ),
        ],
    )
    def delete(self):
        id = int(self.app.pargs.item_id)
        self.app.log.info('deleting todo item id: %s' % id)
        self.app.db.remove(doc_ids=[id])
```

{% endcode %}

And lets delete our completed item:

```
$ todo delete 2
INFO: deleting todo item id: 2

$ todo list
1 [ ] Call Saul
3 [ ] Meet with Jessie About a Thing
```

{% endtab %}
{% endtabs %}

## Conclusion

That concludes Part 2!  We now have a fully functional TODO application.  In the next parts we will discuss more indepth about extending the project with plugins, and digging deeper on things like documentation and testing.


# Part 3: Extending a Project

## FIXME - Coming Soon

* Defining Hooks
* Defining Interfaces
* Creating Plugins


# Part 4: Making Everything Legit

## FIXME - Coming Soon

* Documentation
* Unit Testing
* Distribution and Packaging


# Core Foundation


# Interfaces and Handlers

## Introduction to Interfaces

Cement builds upon a standard interface and handler system that is used extensively to break up pieces of the framework into relatable chunks, and allow customization of everything from logging to config file parsing, and almost every operation in between.

{% hint style="info" %}
In Cement, an interface is what **defines** some functionality, and a handler is what **implements** that functionality.
{% endhint %}

We call the implementation of an interface a **handler**, and provide the ability to easily register and retrieve them via the `app.handler` object. Cement interfaces are defined as [Python Abstract Base Classes](https://docs.python.org/3/library/abc.html), and handlers implement them by sub-classing and overriding the defined abstract methods required to make the implementation legit.

**API References**

* [Cement Core Interface Module](https://cement.readthedocs.io/en/3.0/api/core/interface/)
* [Cement Core Handler Module](https://cement.readthedocs.io/en/3.0/api/core/handler/)

### Builtin Interfaces

The following interfaces are builtin to Cement's core foundation:

| **Interface**                                                                                                             | **Description**                                                                                                                                 |
| ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| [**Extension**](/core-foundation/extensions-1)                                                                            | Framework extension loading.                                                                                                                    |
| [**Log**](https://cement.readthedocs.io/en/portland/api/core/log/#cement.core.log.LogHandler)                             | Messaging to console, and/or file via common log facilities (INFO, WARNING, ERROR, FATAL, DEBUG).                                               |
| [**Config**](https://cement.readthedocs.io/en/portland/api/core/config/#cement.core.config.ConfigHandler)                 | Merging of application configuration defaults, configuration files, and environment settings into a single config object.                       |
| [**Mail**](https://cement.readthedocs.io/en/portland/api/core/mail/#cement.core.mail.MailHandler)                         | Remote message sending (email, smtp, etc).                                                                                                      |
| [**Plugin**](https://cement.readthedocs.io/en/portland/api/core/plugin/#cement.core.plugin.PluginHandler)                 | Application plugin loading.                                                                                                                     |
| [**Template**](https://cement.readthedocs.io/en/portland/api/core/template/#cement.core.template.TemplateHandler)         | Rendering of template data (content, files, etc).                                                                                               |
| [**Output**](https://cement.readthedocs.io/en/portland/api/core/output/#cement.core.output.OutputHandler)                 | Rendering of data/content to end-user output (console text from template, JSON, Yaml, etc).  Often uses an associated template handler backend. |
| [**Argument**](https://cement.readthedocs.io/en/portland/api/core/arg/#cement.core.arg.ArgumentHandler)                   | Command line argument/option parsing.                                                                                                           |
| [**Controller**](https://cement.readthedocs.io/en/portland/api/core/controller/#cement.core.controller.ControllerHandler) | Command dispatch (sub-commands, arguments, etc)                                                                                                 |
| [**Cache**](https://cement.readthedocs.io/en/portland/api/core/cache/#cement.core.cache.CacheHandler)                     | Key/Value data store (memcached, redis, etc)                                                                                                    |

### Working With Interfaces

The [InterfaceManager](https://cement.readthedocs.io/en/3.0/api/core/interface/#cement.core.interface.InterfaceManager) (`app.interface`) provides quick mechanisms to list, get, and verify interfaces:

```python
from cement import App

with App('myapp') as app:
    # list defined interfaces
    app.interface.list()

    # get an interface class
    i = app.interface.get('output')

    # validate if an interface is defined
    app.interface.defined('mail')
```

### Defining an Interface

{% hint style="warning" %}
Defining interfaces is more of an advanced topic, and is not required to fully grasp for new developers or those new to the framework.
{% endhint %}

Cement uses interfaces and handlers extensively to manage the framework, however developers can also make use of this system to provide a clean, and standardized way of allowing other developers to customize their application (generally via application plugins).

The following defines a basic interface we'll call `greeting`:

```python
from abc import abstractmethod
from cement import App, Interface

​class GreetingInterface(Interface):
    class Meta:
        interface = 'greeting'

    @abstractmethod
    def _get_greeting(self):
        """
        Get a greeting message for the end-user.

        Returns:
            greeting (str): The greeting string to present to
                the end-user.
        """
        pass

    @abstractmethod
    def greet(self):
        """
        Display a greeting message for the end-user.

        Returns: None
        """
        pass

class MyApp(App):
    label = 'myapp'
    interfaces = [
        GreetingInterface,
    ]
```

The above example defines the `greeting` interface, by providing abstract methods that any handlers implementing this interface must provide. It does not implement any functionality on its own (though it could), but rather defines and documents its purpose and its expected implementation. The interface is easily defined with the framework by listing it in `App.Meta.interfaces`, but you can also define interfaces directly with `app.interface.define()`.

### Implementing an Interface

In order to implement the above `greeting` interface, we first want to provide a handler base class that will be the starting point for all implementations that sub-class from it:

```python
from cement import Handler

class GreetingHandler(GreetingInterface, Handler):

    def greet(self):
        self.app.log.debug('about to greet end-user')
        msg = self._get_greeting()
        assert isinstance(str, msg), "The msg is not a string!"
        print(msg)
```

{% hint style="info" %}
Handler base classes sub-class from both the interface they are implementing (`GreetingInterface`), and also the Cement Handler base class (`Handler`). The application developer defining the interface should always provide a handler base class for the implementation, even if the base class does not fully satisfy the interface.
{% endhint %}

In the above example, the developer would call the `greet()` method that will do all of the common operations like logging, exception handling, etc for all implementations, leaving only the minimal `_get_greeting()` method to be provided by the final implementation sub-classes. This follows the common [Don't Repeat Yourself (DRY)](https://en.wikipedia.org/wiki/Don't_repeat_yourself) principle's best practice (all-be-it a tediously simple example), where all of the reusable logic can live in one place, and sub-classes only focus on their unique means of implementing an interface.

In order to complete our implementation of the above `greeting` interface, we can now sub-class from the provided `GreetingHandler` base class, and fill in the missing pieces:

```python
class Hello(GreetingHandler):
    class Meta:
        label = 'hello'

    def _get_greeting(self):
        return 'Hello!'


class Goodbye(GreetingHandler):
    class Meta:
        label = 'goodbye'

    def _get_greeting(self):
        return 'Goodbye!'
```

{% hint style="info" %}
An interface defines itself to the framework via the `Interface.Meta.interface` string, and a handler defines itself via the `Handler.Meta.label` string. Collectively, all implementation handlers are referred to by both as `<interface>.<label>` or in the above examples `greeting.hello` and `greeting.goodbye`.
{% endhint %}

### Putting It All Together

The following is an [MCVE](/terminology#minimal-complete-verifiable-example-mcve) of defining an interface, providing an implementation handler base class, and registering multiple handlers that implement the interface differently:

{% tabs %}
{% tab title="myapp.py" %}

```python
from abc import abstractmethod
from cement import App, Interface, Handler

class GreetingInterface(Interface):
    class Meta:
        interface = 'greeting'

    @abstractmethod
    def _get_greeting(self):
        """
        Get a greeting message for the end-user.

        Returns:
            greeting (str): The greeting string to present to
                the end-user.
        """
        pass

    @abstractmethod
    def greet(self):
        """
        Display a greeting message for the end-user.

        Returns: None
        """
        pass


class GreetingHandler(GreetingInterface, Handler):

    def greet(self):
        self.app.log.debug('about to greet end-user')
        msg = self._get_greeting()
        assert isinstance(msg, str), "The msg is not a string!"
        print(msg)


class Hello(GreetingHandler):
    class Meta:
        label = 'hello'

    def _get_greeting(self):
        return 'Hello!'


class Goodbye(GreetingHandler):
    class Meta:
        label = 'goodbye'

    def _get_greeting(self):
        return 'Goodbye!'


class MyApp(App):
    class Meta:
        label = 'myapp'

        interfaces = [
            GreetingInterface,
        ]

        handlers = [
            Hello,
            Goodbye,
        ]

with MyApp() as app:
    app.run()
    g = app.handler.get('greeting', 'hello', setup=True)
    g.greet()
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
Hello!

$ python myapp.py -l debug
2018-07-17 20:28:21,449 (DEBUG) myapp : about to greet end-user
Hello!
```

{% endtab %}
{% endtabs %}

## Introduction to Handlers

Where an interface defines what an implementation is expected to provide, a handler is what actually implements the interface.

### Working with Handlers

The [HandlerManager](https://cement.readthedocs.io/en/3.0/api/core/handler/#cement.core.handler.HandlerManager) (`app.handler`) provides quick mechanisms to list, get, resolve and verify handlers. The following are a few examples of working with handlers:

```python
from cement import App

​with App('myapp') as app:
    # get a log handler called logging
    lh = app.handler.get('log', 'logging', setup=True)​

    # List all handlers registered to the config interface
    app.handler.list('config')​

    # check if the handler argparse is registered
    # to the argument interface
    app.handler.registered('argument', 'argparse')

    # resolve a handler by string, class, or object
    app.handler.resolve('log', 'logging')
    app.handler.resolve('log', LoggingLogHandler)
    app.handler.resolve('log', LoggingLogHandler())
```

{% hint style="info" %}
It is important to note that handlers are stored within the application as uninstantiated objects. Meaning you must instantiate them after retrieval (call `_setup(app)`) or simply pass `setup=True` to the `app.handler.get()` method.
{% endhint %}

### Registering Handlers to an Interface

An interface simply defines what an implementation is expected to provide, whereas a handler actually implements the interface.

{% tabs %}
{% tab title="Registering a Handler to an Interface" %}
The following is a simple example of sub-classing an existing handler, then registering that with the framework.

```python
from cement import App
from cement.ext.ext_configparser import ConfigParserConfigHandler

class MyConfigHandler(ConfigParserConfigHandler):
    class Meta:
        label = 'my_config_handler'

    # do something to sub-class ConfigParserConfigHandler

class MyApp(App):
    class Meta:
        label = 'myapp'
        handlers = [MyConfigHandler]
```

{% endtab %}
{% endtabs %}

### Overriding Default Handlers <a href="#overriding-default-handlers" id="overriding-default-handlers"></a>

Cement sets up a number of default handlers for logging, config parsing, etc. These can be overridden in a number of ways, however the primary method is to override their associated setting in [App.Meta](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta).

{% tabs %}
{% tab title="Overriding Default Handlers" %}
Using the above `MyConfigHandler` example, we simply need to register a handler to an interface, and then override the `App.Meta.config_handler` option:

```python
class MyApp(App):
    class Meta:
        label = 'myapp'
        handlers = [MyConfigHandler]
        config_handler = 'my_config_handler'
```

{% endtab %}
{% endtabs %}

All builtin core interfaces have an associated `App.Meta.x_handler` option, allowing complete customization of every aspect of the framework. See the reference documentation of [App.Meta](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta) for more detail.

### Multiple Registered Handlers <a href="#multiple-registered-handlers" id="multiple-registered-handlers"></a>

All handlers and interfaces are unique. In most cases, where the framework is concerned, only one handler is used. For example, whatever is configured for the [`App.Meta.log_handler`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.log_handler) will be used and setup as `app.log`. However, take for example an Output Handler. You might have a default [`App.Meta.output_handler`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.output_handler) of `mustache` (a text templating language) but may also want to override that handler with the `json` output handler when `-o json` is passed at command line. In order to allow this functionality, both the `mustache` and `json` output handlers must be registered.

Any number of handlers can be registered to an interface. You might have a use case for an Interface/Handler that may provide different compatibility based on the operating system, or perhaps based on simply how the application is called. A good example would be an application that automates building packages for Linux distributions. An interface would define what a build handler needs to provide, but the build handler would be different based on the OS. The application might have an `rpm` build handler, or a `dpkg` build handler to perform the build process differently.

### Customizing Handler Configuration and Meta <a href="#customizing-handlers" id="customizing-handlers"></a>

Depending on the handler, you will have different ways of customizing its functionality. Some handlers honor application configuration setting, while others may only rely on meta-options. In either case, both can be modified at the top level of your application meta.

In the following example, we modify the configuration *defaults* of the log handler, and also the meta-options to enable an optional log level command line argument feature it supports.

{% hint style="warning" %}
Note that configuration settings are always overridable via configuration files, however this example is modifying the builtin default setting of the log handler.
{% endhint %}

{% tabs %}
{% tab title="Example: Customizing Handler Configuration and Meta" %}

```python
from cement import App, init_defaults

CONFIG = init_defaults('myapp', 'log.logging')
CONFIG['log.logging']['level'] = 'warning'

META = init_defaults('log.logging')
META['log.logging']['log_level_argument'] = ['-l', '--level']

class MyApp(App):
    class Meta:
        label = 'myapp'
        config_defaults = CONFIG
        meta_defaults = META
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
If modifying the configuration or meta options isn't enough, you can always sub-class an existing handler and register your own in its place.
{% endhint %}

### Overriding Handlers via Command Line <a href="#overriding-handlers-via-command-line" id="overriding-handlers-via-command-line"></a>

In some use cases, you will want the end user to have access to override the default handler of a particular interface. For example, Cement ships with multiple Output Handlers including `json`, `yaml`, and `mustache`. A typical application might default to using `mustache` to render console output from text templates. That said, without changing any code in the application, the end user could simply pass the `-o json` command line option and output the same data that is rendered to template, out in pure JSON.

{% hint style="warning" %}
Output hander overrides are not enabled by default, but can be enabled by setting the `OutputHandler.Meta.overridable` option to `True` for the output handlers that you want overridable by the `-o` option at command line. See the documentation on [Output Rendering](/core-foundation/output-rendering) for more details and examples.
{% endhint %}

The only built-in handler override that Cement includes is for the above mentioned JSON example, but you can add any that your application requires.

{% tabs %}
{% tab title="Example: Overriding Handlers via Command Line" %}
{% code title="myapp.py" %}

```python
from cement import App, init_defaults

META = init_defaults('output.json', 'output.yaml')
META['output.json']['overridable'] = True
META['output.yaml']['overridable'] = True

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['json', 'yaml', 'mustache']
        meta_defaults = META
        output_handler = 'mustache'
        template_dir = './templates'

with MyApp() as app:
    app.run()

    data = {'foo': 'bar'}
    app.render(data, 'example.m')
```

{% endcode %}

{% code title="templates/example.m" %}

```
Foo: {{ foo }}
```

{% endcode %}
{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py --help
usage: myapp [-h] [-d] [-q] [-o {json,yaml}]

optional arguments:
  -h, --help      show this help message and exit
  -d, --debug     full application debug mode
  -q, --quiet     suppress all console output
  -o {json,yaml}  output handler

$ python myapp.py
Foo: bar

$ python myapp.py -o json
{"foo": "bar"}

$ python myapp.py -o yaml
foo: bar
```

{% endtab %}
{% endtabs %}

Notice the `-o` command line option, that includes the choices: `yaml` and `json`. This feature will include all Output Handlers that have the `overridable` meta-data option set to `True`. We did not set this option for the mustache handler, therefore it did not show up as a choice for the `-o` option at command-line.


# Hooks

## Introduction to Hooks

Hooks allow developers to tie into different pieces of the framework and an application.

A hook can be defined anywhere, be it internally in the application, or in a plugin, extension, etc. Once a hook is defined, functions can be registered to that hook so that when the hook is called, all functions registered to that hook will be run. By defining a hook, you are saying that you are going to honor that hook somewhere in your application. Using descriptive hook names are good for clarity. For example, `pre_database_connect` is obviously a hook that will be run before a database connection is attempted.

{% hint style="info" %}
The most important thing to remember when defining hooks for your application is to properly document them. Include whether anything is expected in return or what, if any, arguments will be passed to the hook functions when called.
{% endhint %}

**API Reference:**

* ​[Cement Hook Module](https://docs.builtoncement.com/%7B%7B%20version%20%7D%7D/api/core/hook.html)​

## **Configuration**

### **Application Meta Options**

The following options under [`App.Meta`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta) modify hook handling:

| **Option**        | **Description**                         |
| ----------------- | --------------------------------------- |
| **define\_hooks** | List of hook labels to define hooks by. |
| **hooks**         | List of hooks to be registered.         |

## Working with Hooks

The [`HookManager`](https://cement.readthedocs.io/en/3.0/api/core/hook/#cement.core.hook.HookManager) provides mechanisms for defining, registering, and executing hooks.

{% tabs %}
{% tab title="Example: Working with Hooks" %}

```python
from cement import App

def some_function():
    pass

with App('myapp') as app:
    # list all defined hooks
    app.hook.list()

    # define a hook
    app.hook.define('my_example_hook')

    # test if a hook is defined
    app.hook.defined('my_example_hook')

    # register a function to a hook
    app.hook.register('my_example_hook', some_function)

    # run a hook
    for res in app.hook.run('my_example_hook'):
        # do something with res...
        pass
```

{% endtab %}
{% endtabs %}

## Defining a Hook

A hook can be defined anywhere. However it is generally recommended to define the hook as early as possible. A hook definition simply gives a label to the hook, and allows the developer (or third-party plugin developers) to register functions to that hook. Its label is arbitrary.

The most convenient way to define a hook is via [`CementApp.Meta.define_hooks`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.define_hooks):

{% tabs %}
{% tab title="Example: Defining Hooks via App" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        define_hooks = [
            'my_example_hook',
        ]
```

{% endtab %}
{% endtabs %}

Alternatively, hooks can be defined by extensions or plugins via the hook manager directly:

{% tabs %}
{% tab title="Example: Defining Hooks via Extensions/Plugins" %}

```python
def load(app):
    app.hook.define('my_example_hook')
```

{% endtab %}
{% endtabs %}

## Registering Functions to a Hook

A hook is just an identifier, but the functions registered to that hook are what get run when the hook is called. Registering a hook function should also be done early on in the runtime process, any time after the application has been created, after the hook is defined, and before the hook is run. Note that every hook is different, and therefore should be clearly documented by the owner of the hook (application developer, plugin developer, etc).

The most convenient way to register a hook function is via [`CementApp.Meta.hooks`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.hooks):

{% tabs %}
{% tab title="Example: Registering Functions to a Hook" %}

```python
from cement import App

def my_hook_function(app):
    # do something with app
    pass

class MyApp(App):
    class Meta:
        label = 'myapp'
        hooks = [
            ('pre_setup', my_hook_function),
        ]
```

{% endtab %}
{% endtabs %}

Alternatively, hooks can be registered by extensions or plugins via the hook manager directly:

{% tabs %}
{% tab title="Example: Registering Hooks via Extensions/Plugins" %}

```python
def my_hook_function(app):
    # do something with app
    pass

def load(app):
    app.hook.register('pre_setup', my_hook_function)
```

{% endtab %}
{% endtabs %}

## Hook Parameters and Return Values

What you receive from a hook (arguments, keyword arguments), and what you return from your hook function depends on what the developer who owns the hook has defined. Each hook is different, and the nature of the hook determines whether you need to accept arguments, or return anything.

{% hint style="warning" %}
It is important that the owner of the hook (application/plugin developer, etc) properly document the usage of the hook including the `*args`, `**kwargs` it is sending as well as what it is expecting in return.
{% endhint %}

## Running a hook

Now that a hook is defined, and functions have been registered to that hook all that is left is to run it. Keep in mind, you don't want to run a hook until after the application load process... meaning, after all plugins and other code are loaded. If you receive an error that the hook doesn't exist, then you are likely trying to register a hook too soon before the hook is defined. Likewise, if it doesn't seem like your hook is running and you don't see it mentioned in `--debug` output, you might be registering your hook **after** the hook has already run.

{% tabs %}
{% tab title="Example: Running a Hook" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        define_hooks = ['my_example_hook']

with MyApp() as app:
    for res in app.hook.run('my_example_hook'):
        # do something with res
        pass
```

{% endtab %}
{% endtabs %}

As you can see we iterate over the hook, rather than just calling `app.hook.run()` by itself. This is necessary because `app.hook.run()` yields the results from each hook function as they are run. Hooks can be run anywhere *after* the hook is defined, and hooks are registered to that hook.

## Controlling Hook Run Order

Sometimes you might have a very specific purpose in mind for a hook, and need it to run before or after other functions in the same hook. For that reason there is an optional `weight` parameter that can be passed when registering a hook function.

{% tabs %}
{% tab title="Example: Controlling Hook Run Order" %}

```python
from cement import App

def func1(app):
    print('Inside func1()')

def func2(app):
    print('Inside func2()')

def func3(app):
    print('Inside func3()')


class MyApp(App):
    class Meta:
        label = 'myapp'

        hooks = [
            ('pre_setup', func1, 0),
            ('pre_setup', func2, 100),
            ('pre_setup', func3, -99),
        ]

with MyApp() as app:
    app.run()
```

{% endtab %}

{% tab title="cli" %}

```
$ python tmp/myapp.py
Inside func3()
Inside func1()
Inside func2()
```

{% endtab %}
{% endtabs %}

As you can see, it doesn’t matter what order we register the hook, the weight runs them in order from lowest to highest based on their `weight` value.

Alternatively, with a plugin or extension:

{% tabs %}
{% tab title="Example: Controlling Hook Run Order via Extension/Plugin" %}

```python
def func1():
    pass

def load(app):
    app.hook.register('my_example_hook', func1, weight=10)
```

{% endtab %}
{% endtabs %}

## Cement Framework Hooks

Cement defines a number of hooks that tie into the framework.

| **Hook Name**               | **Description**                                                                                                                                                                                                                                                                                                                                                 |
| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **pre\_setup**              | Run first when `App.setup()` is called. The application object is passed as an argument.  Nothing is expected in return.                                                                                                                                                                                                                                        |
| **post\_setup**             | Run last when `App.setup()` is called. The application object is passed as an argument. Nothing is expected in return.                                                                                                                                                                                                                                          |
| **pre\_run**                | Run first when `App.run()` is called. The application object is passed as an argument. Nothing is expected in return.                                                                                                                                                                                                                                           |
| **post\_run**               | Run last when `App.run()` is called. The application object is passed as an argument. Nothing is expected in return.                                                                                                                                                                                                                                            |
| **pre\_argument\_parsing**  | Run after `App.run()` is called, just *before* argument parsing happens. The application object is passed as an argument to these hook functions. Nothing is expected in return.                                                                                                                                                                                |
| **post\_argument\_parsing** | Run after `App.run()` is called, just *after* argument parsing happens. The application object is passed as an argument to these hook functions. Nothing is expected in return.This hook is generally useful where the developer needs to perform actions based on the arguments that were passed at command line, but before the logic of `App.run()` happens. |
| **pre\_render**             | Run first when `App.render()` is called. The application object, and data dictionary are passed as arguments. Must return either the original data dictionary, or a modified one.                                                                                                                                                                               |
| **post\_render**            | Run last when `App.render()` is called. The application object, and rendered output text are passed as arguments. Must return either the original output text, or a modified version.                                                                                                                                                                           |
| **pre\_close**              | Run first when `App.close()` is called. This hook should be used by plugins and extensions to do any 'cleanup' at the end of program execution. Nothing is expected in return.                                                                                                                                                                                  |
| **post\_close**             | Run last when `App.close()` is called. Most use cases need `pre_close`, however this hook is available should anyone need to do anything after all other cleanup operations.                                                                                                                                                                                    |
| **signal**                  | Run when signal handling is enabled, and the defined signal handler callback is executed. This hook should be used by the application, plugins, and extensions to perform any actions when a specific signal is caught. Nothing is expected in return.                                                                                                          |


# Configuration Settings

## Introduction to the Config Interface

Cement defines a [Config Interface](http://cement.readthedocs.io/en/3.0/api/core/config/#cement.core.config.ConfigInterface), as well as the default [ConfigParserConfigHandler](http://cement.readthedocs.io/en/3.0/api/ext/ext_configparser/#cement.ext.ext_configparser.ConfigParserConfigHandler) that implements the interface. This handler is built on top of [ConfigParser](http://docs.python.org/library/configparser.html) which is included in the Python standard library. Therefore, this class will work much like ConfigParser but with any added functions necessary to meet the requirements of the interface.

{% hint style="warning" %}
Cement often includes multiple handler implementations of an interface that may or may not have additional features or functionality than the interface requires. The documentation below only references usage based on the interface and default handler (not the full capabilities of an implementation).
{% endhint %}

**Cement Extensions That Provide Config Handlers:**

* [ConfigParser](/extensions/configparser) *(default)*
* [Json](/extensions/json)
* [Yaml](/extensions/yaml)

**API References:**

* [Cement Core Config Module](https://cement.readthedocs.io/en/3.0/api/core/config/)
* [Cement ConfigParser Extension](https://cement.readthedocs.io/en/3.0/api/ext/ext_configparser/)
* [Python ConfigParser Library](https://docs.python.org/3/library/configparser.html)

## **Configuration**

### **Application Meta Options**

The following options under [`App.Meta`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta) modify configuration handling:

| **Option**               | **Description**                                                                                                                                                                       |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **config\_defaults**     | Default configuration dictionary.                                                                                                                                                     |
| **config\_dirs**         | List of configuration directory paths where config files will be loaded from.  These are merged together with `App.Meta.core_system_config_dirs` and `App.Meta.core_user_config_dirs` |
| **config\_file\_suffix** | The suffix (extension) of configuration files.  Default: `.conf`                                                                                                                      |
| **config\_files**        | List of configuration file paths to load.                                                                                                                                             |
| **config\_handler**      | The configuration handler that implements the config interface.                                                                                                                       |
| **config\_section**      | The section label of the application's configuration within config files. Defaults: `App.Meta.label`                                                                                  |

## Configuration Load Order

An application's configuration is made up of a number of things, including default settings, handler defaults, config file settings, environment variables, etc. The following is the order in which configurations are discovered and loaded:

* Defaults defined in [`App.Meta.config_defaults`](http://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.config_defaults)
* Extended by [`Handler.Meta.config_defaults`](http://cement.readthedocs.io/en/3.0/api/core/handler/#cement.core.handler.Handler.Meta.config_defaults) *(extended, not overridden)*
* Overridden by configuration files defined in [`App.Meta.config_files`](http://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.config_files) in the order they are listed/loaded (last has precedence)
* Overridden by environment variables (ex: `$MAPP_FOO` `$MYAPP_LOG_LOGGING_LEVEL`, etc)

## Application Default Settings

Cement does not require default config settings in order to operate. That said, these settings are found under the `App.Meta.label` section of the configuration, and overridden by a `[<app_label>]` block from configuration files.

{% tabs %}
{% tab title="Example: Setting Application Defaults" %}
{% code title="myapp.py" %}

```python
from cement import App, init_defaults


CONFIG = init_defaults('myapp', 'log.logging')
CONFIG['myapp']['foo'] = 'bar'
CONFIG['log.logging']['level'] = 'info'

class MyApp(App):
    class Meta:
        label = 'myapp'
        config_defaults = CONFIG
```

{% endcode %}

{% code title="\~/.myapp.conf" %}

```
[myapp]
foo = bar

[log.logging]
level = info
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
Note that `init_defaults` is a helper from the Miscellaneous Utility Module, and simply generates a dict with nested dicts of the given keys. It does not do anything special, but is used throughout the documentation as it generally makes things more readable in examples.

You can always use a standard `dict` for configuration and meta defaults, which often makes more sense when building larger applications with a lot of default settings to manage.
{% endhint %}

## Builtin Default Configuration Settings

Cement defines a list of meta options that can be overridden by configuration settings in [`App.Meta.core_meta_override`](http://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.core_meta_override) (used by the framework), and [`App.Meta.meta_override`](http://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.meta_override) (used by the application developer). These are not required to exist in the config defaults or parsed configuration files. However, if they do, Cement will honor them and override the defined application meta options.

## Configuration File Loading

Cement defines the following builtin default configuration file paths:

```
/etc/myapp/myapp.conf
~/.config/myapp/myapp.conf
~/.myapp/config/myapp.conf
~/.myapp.conf
```

We also define the following configuration directories to scan for additional configuration files for extensions and plugins:

```
/etc/myapp/ext.d
/etc/myapp/plugins.d
~/.config/myapp/ext.d
~/.config/myapp/plugins.d
~/.myapp/config/ext.d
~/.myapp/config/plugins.d
```

{% hint style="info" %}
These lists are dynamically generated based on the `App.meta.label`, as well as [`App.meta.config_file_suffix`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.config_file_suffix). They can be extended by adding files via [`App.Meta.config_files`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.config_files) or directories to [`App.Meta.config_dirs`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.config_dirs).
{% endhint %}

## Accessing Configuration Settings

After application creation and setup, you can access the config handler via the `app.config` object.

{% tabs %}
{% tab title="Example: Using App Config Object" %}

```python
from cement import App

with App('myapp') as app:
    app.run()

    ​# get a setting
    app.config.get('myapp', 'debug')

    ​# set settings
    app.config.set('myapp', 'debug', True)

    ​# get a list of sections
    app.config.get_sections()​

    # add a section
    app.config.add_section('my_config_section')

    ​# test if a section exists
    app.config.has_section('my_config_section')​

    # get configuration keys for the 'myapp' section
    app.config.keys('myapp')​

    # test if a key exists
    if 'debug' in app.config.keys('myapp')​:
        pass

    # merge a dict of settings into the config
    other_config = {
        'myapp': {
            'foo': 'not bar',
        }
    }
    app.config.merge(other_config)

    # parse a file into the config
    app.config.parse('/path/to/file')

    # get a dict of the entire config
    app.config.get_dict()
```

{% endtab %}
{% endtabs %}

## Configuration Settings vs. Meta Options

As you will see extensively throughout the Cement code is the use of meta options. There can be some confusion between the use of meta options, and application configuration settings.

{% hint style="info" %}
The key detail to note is that configuration settings are intended to be used and modified by the **end-user**, whereas meta options are intended to be used by the application **developer** to alter the application's core functionality.
{% endhint %}

**Configuration Settings**

Configuration settings are application specific. There are config defaults defined by the application developer, that can be (and are intended to be) overridden by end-user defined settings in a configuration file.

Cement does not rely on the application configuration, though it can honor configuration settings. For example, `App` honors the `debug` config option which is documented, but it doesn't rely on it existing either.

The key things to note about application configuration settings are:

* They give the **end-user** flexibility in how the application operates.
* Anything that you want users to be able to customize via a config file should be defined in the application's configuration. For example, the path to a log file or the location of a database server. These are things that you do not want hard-coded into your app, but rather should have sane and functional defaults for.

**Meta Options**

Meta options are used on the backend by developers to alter how classes operate. For example, the [`App.Meta.log_handler`](http://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.log_handler) defines the default log handler as `logging` (`cement.ext.ext_logging.LoggingLogHandler`), however because this is built on an interface definition, Cement can use any other log handler the same way without issue as long as that log handler properly implements the interface definition. Meta options make this change seamless and allows the handler to alter functionality, rather than having to change code in the top level class itself.

The key thing to note about meta options are:

* They give the **developer** flexibility in how the code operates.
* End users should not have access to modify meta options via a config file or similar 'dynamic' configuration unless explicitly listed in [`Cement.Meta.core_meta_override`](http://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.core_meta_override) or [`CementApp.Meta.meta_override`](http://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.meta_override) (for example, the `debug` setting under the `[<app_label>]` section overrides `App.Meta.debug` by default.
* Meta options are used to alter how classes work, but they are considered 'hard-coded' settings. If the developer chooses to alter a meta option, it is for the life of that release.
* Meta options should have a sane default, and be clearly documented.

## Application Defaults vs Handler Defaults

There may be slight confusion between the [`App.Meta.config_defaults`](http://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.config_defaults) and the [`Handler.Meta.config_defaults`](http://cement.readthedocs.io/en/3.0/api/core/handler/#cement.core.handler.Handler.Meta.config_defaults) meta options. They both are very similar, however the application level configuration defaults are intended to be used to set defaults for multiple sections. Therefore, the `App.Meta.config_defaults` option is a `dict` with nested `dict`s under it. Each key of the top level `dict` relates to a config `[section]` and the nested `dict`s are the settings for that `[section]`.

The `Handler.Meta.config_defaults` only pertain to a single `[section]` and therefore is only a single level `dict`, whose settings are applied to that section of the application's configuration (defined by [`Handler.Meta.config_section`](http://cement.readthedocs.io/en/3.0/api/core/handler/#cement.core.handler.Handler.Meta.config_section)).

## Creating a Config Handler

All interfaces in Cement can be overridden with your own implementation. This can be done either by sub-classing [`ConfigHandler`](https://cement.readthedocs.io/en/3.0/api/core/config/#cement.core.config.ConfigHandler) itself, or by sub-classing an existing extension's handlers in order to alter their functionality.

{% tabs %}
{% tab title="Example: Creating a Config Handler" %}
{% code title="myapp.py" %}

```python
from cement import App
from cement.core.config import ConfigHandler

class MyConfigHandler(ConfigHandler):
    class Meta:
        label = 'my_config_handler'

    # do something to implement the interface

class MyApp(App):
    class Meta:
        label = 'myapp'
        config_handler = 'my_config_handler'
        handlers = [
            MyConfigHandler,
        ]
```

{% endcode %}
{% endtab %}
{% endtabs %}


# Arguments

## Introduction to the Argument Interface

Cement defines an [Argument Interface](https://cement.readthedocs.io/en/3.0/api/core/arg/#cement.core.arg.ArgumentInterface), as well as the default [ArgParseArgumentHandler](https://cement.readthedocs.io/en/3.0/api/core/arg/#cement.core.arg.ArgumentHandler) that implements the interface. This handler is built on top of the [ArgParse](http://docs.python.org/library/argparse.html) module which is included in the Python standard library.

{% hint style="warning" %}
Cement often includes multiple handler implementations of an interface that may or may not have additional features or functionality than the interface requires. The documentation below only references usage based on the interface and default handler (not the full capabilities of an implementation).
{% endhint %}

**Cement Extensions That Provide Argument Handlers:**

* [Argparse](/extensions/argparse)

**API References:**

* [Cement Core Argument Module](https://cement.readthedocs.io/en/3.0/api/core/arg/)
* [Cement Argparse Extension](https://cement.readthedocs.io/en/3.0/api/ext/ext_argparse)

## **Configuration**

### **Application Meta Options**

The following options under [`App.Meta`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta) modify configuration handling:

| **Option**       | **Description**                                     |
| ---------------- | --------------------------------------------------- |
| **arg\_handler** | The handler that implements the argument interface. |

## Adding Arguments

The argument interface is loosely based on Argparse, but only defines a minimal set of params that must be honored as to ensure that the framework and extensions can add arguments regardless of what the argument handler implementation is. That said, Cement has never intended to use anything other than Argparse to handle arguments and for that reason there may be some assumptions inherently builtin that assume the underlying argument handler is 100% argparse compliant. For that reason, adding and working with arguments will be completely familiar for anyone who has ever used Argparse.

{% tabs %}
{% tab title="Example: Adding Arguments" %}

```python
from cement import App

with App('myapp') as app:
    # add arguments before app.run()
    app.args.add_argument('-f', '--foo', 
                          action='store', 
                          dest='foo')                     

    # run the application (parses arguments)
    app.run()
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py --help
usage: myapp [-h] [-d] [-q] [-f FOO]

optional arguments:
  -h, --help         show this help message and exit
  -d, --debug        full application debug mode
  -q, --quiet        suppress all console output
  -f FOO, --foo FOO
```

{% endtab %}
{% endtabs %}

## Accessing Parsed Arguments

During `app.run()`, command line arguments are parsed by the argument handler, and the results are stored by the application. Arguments are then accessible by [`App.pargs`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.pargs) (parsed args).

{% tabs %}
{% tab title="Example: Accessing Parsed Arguments" %}

```python
from cement import App

with App('myapp') as app:
    # add arguments before app.run()
    app.args.add_argument('-f', '--foo', 
                          action='store', 
                          dest='foo')                     

    # run the application (parses arguments)
    app.run()

    # test if argument was passed
    if app.pargs.foo is not None:
        print('Foo => %s ' app.pargs.foo
```

{% endtab %}
{% endtabs %}

## Creating an Argument Handler

All interfaces in Cement can be overridden with your own implementation. This can be done either by sub-classing [ArgumentHandler](https://cement.readthedocs.io/en/3.0/api/core/template/#cement.core.template.TemplateHandler) itself, or by sub-classing an existing extension's handlers in order to alter their functionality.

{% tabs %}
{% tab title="Example: Creating an Argument Handler" %}
{% code title="myapp.py" %}

```python
from cement import App
from cement.core.arg import ArgumentHandler

class MyArgumentHandler(ArgumentHandler):
    class Meta:
        label = 'my_argument_handler'

    # do something to implement the interface

class MyApp(App):
    class Meta:
        label = 'myapp'
        argument_handler = 'my_argument_handler'
        handlers = [
            MyArgumentHandler,
        ]
```

{% endcode %}
{% endtab %}
{% endtabs %}


# Logging

## Introduction to the Log Interface

Cement defines the [Log Interface](https://cement.readthedocs.io/en/3.0/api/core/log/#cement.core.log.LogInterface), as well as the default [LoggingLogHandler](https://cement.readthedocs.io/en/3.0/api/ext/ext_logging/#cement.ext.ext_logging.LoggingLogHandler) that implements the interface. This handler is built on top of the [Logging](http://docs.python.org/library/logging.html) module which is included in the Python standard library.

{% hint style="warning" %}
Cement often includes multiple handler implementations of an interface that may or may not have additional features or functionality than the interface requires. The documentation below only references usage based on the interface and default handler (not the full capabilities of an implementation).
{% endhint %}

**Cement Extensions That Provide Log Handlers**

* [Logging](/extensions/logging)
* [Colorlog](/extensions/colorlog)

**API References:**

* [Cement Core Log Module](https://cement.readthedocs.io/en/3.0/api/core/log/)
* [Cement Logging Extension](https://cement.readthedocs.io/en/3.0/api/ext/ext_logging/)

## **Configuration**

### **Application Meta Options**

The following options under [`App.Meta`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta) modify configuration handling:

| **Option**       | **Description**                                |
| ---------------- | ---------------------------------------------- |
| **log\_handler** | The handler that implements the log interface. |

## Logging Messages

The following shows logging to each of the defined log levels.

{% tabs %}
{% tab title="Example: Log Levels" %}

```python
from cement import App

with App('myapp') as app:
    app.run()

    ​# log messages to different levels
    app.log.debug('This is a debug message.')
    app.log.info('This is an info message.')​
    app.log.warning('This is a warning message.')
    app.log.error('This is an error message.')
    app.log.fatal('This is a fatal message.')​
```

{% endtab %}
{% endtabs %}

The above is displayed in order of severity. If the log level is set to `INFO`, you will receive all info messages and above including `WARNING`, `ERROR`, and `FATAL`. However, you will not receive `DEBUG` level messages. The same goes for a log level of `WARNING`, where you will receive `WARNING`, `ERROR`, and `FATAL` but you will not receive INFO, or `DEBUG` level messages.

## Changing Log Level

The log level defaults to `INFO`, but can be set via [`LoggingLogHandler.Meta.config_defaults`](https://cement.readthedocs.io/en/3.0/api/ext/ext_logging/#cement.ext.ext_logging.LoggingLogHandler.Meta.config_defaults) or setting the `level` under the log handlers section of the application configuration:

{% tabs %}
{% tab title="Example: Changing Log Level" %}
{% code title="myapp.py" %}

```python
from cement import App, init_defaults

CONFIG = init_defaults('myapp', 'log.logging')
CONFIG['log.logging']['level'] = 'WARNING'

class MyApp(App):
    class Meta:
        label = 'myapp'
        config_defaults = CONFIG
```

{% endcode %}

{% code title="\~/.myapp.conf" %}

```
[myapp]

# ...

[log.logging]
level = WARNING
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
Cement also includes a `--debug` command line option by default. This triggers `App.Meta.debug` and sets the log level to `DEBUG`.
{% endhint %}

## Logging to Console

The default log handler configuration enables logging messages to console.

{% tabs %}
{% tab title="Example: Logging to Console" %}

```python
from cement import App

with App('myapp') as app:
    app.run()

    # log messages to different levels
    app.log.debug('This is a debug message')
    app.log.info('This is an info message')
    app.log.warning('This is an warning message')
    app.log.error('This is an error message')
    app.log.fatal('This is a fatal message')
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
INFO: This is an info message
WARNING: This is a warning message
ERROR: This is an error message
CRITICAL: This is a fatal message
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Console logging can be disabled by setting `to_console` to `False` in either the application defaults, or under the `[log.logging]` section of the applications configuration file.
{% endhint %}

## Logging to File

File logging is disabled by default but can be enabled by setting the `file` setting under the `[log.logging]` section of the application configuration.

{% tabs %}
{% tab title="Example: Logging to File" %}
{% code title="myapp.py" %}

```python
from cement import App, init_defaults

CONFIG = init_defaults('myapp', 'log.logging')
CONFIG['log.logging']['file'] = '/path/to/file.log'

class MyApp(App):
    class Meta:
        label = 'myapp'
        config_defaults = CONFIG
```

{% endcode %}

{% code title="\~/.myapp.conf" %}

```
[myapp]
# ...

[log.logging]
file = /path/to/file.log
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Tips on Debugging

{% hint style="info" %}
The following is specific to the default [`LoggingLogHandler`](https://cement.readthedocs.io/en/3.0/api/ext/ext_logging/#cement.ext.ext_logging.LoggingLogHandler), and is not an requirement of the logging interface.
{% endhint %}

Logging to `app.log.debug()` is pretty straightforward. However, adding an additional parameter for the `namespace` can greatly increase insight into where that log is happening. The `namespace` defaults to the application name which you will see in every log like this:

```
2012-07-30 18:05:11,357 (DEBUG) myapp : This is my message
```

For debugging, it might be more useful to change this to `__name__`:

```python
app.log.debug('This is my info message', __name__)
```

Which looks like:

```
2012-07-30 18:05:11,357 (DEBUG) myapp.somepackage.test : This is my message
```

Or even more verbose, you might prefer adding something like `__file__` and the function or class method:

```python
app.log.debug('This is my info message', '%s : my_func()' % __file__)
```

Which would look like:

```
2012-07-30 18:05:11,357 (DEBUG) myapp/somepackage/test.py : my_func() : This is my message
```

## Creating a Log Handler

All interfaces in Cement can be overridden with your own implementation. This can be done either by sub-classing [`LogHandler`](https://cement.readthedocs.io/en/3.0/api/core/log/#cement.core.log.LogHandler) itself, or by sub-classing an existing extension's handlers in order to alter their functionality.

{% tabs %}
{% tab title="Example: Creating a Log Handler" %}
{% code title="myapp.py" %}

```python
from cement import App
from cement.core.log import LogHandler

class MyLogHandler(LogHandler):
    class Meta:
        label = 'my_log_handler'

    # do something to implement the interface

class MyApp(App):
    class Meta:
        label = 'myapp'
        log_handler = 'my_log_handler'
        handlers = [
            MyLogHandler,
        ]
```

{% endcode %}
{% endtab %}
{% endtabs %}


# Controllers

## Introduction to the Controller Interface

Cement defines a [Controller Interface](https://cement.readthedocs.io/en/3.0/api/core/controller/#cement.core.controller.ControllerInterface), but does not enable any handlers that implement the interface by default.

{% hint style="info" %}
For convenience, the preferred `ArgparseController` and `expose()` decorator from the [Argparse Extension](/extensions/argparse) are available as `Controller` and `ex` in the top level cement module.
{% endhint %}

Using application controllers is not necessary, but enables rapid development by wrapping pieces of the framework like adding arguments, and linking commands with controller methods. The examples below use the [`ArgparseController`](https://cement.readthedocs.io/en/3.0/api/ext/ext_argparse/#cement.ext.ext_argparse.ArgparseController) as examples (again, imported as `cement.Controller` for convenience).

{% hint style="warning" %}
Cement often includes multiple handler implementations of an interface that may or may not have additional features or functionality than the interface requires. The documentation below only references usage based on the interface and default handler (not the full capabilities of an implementation).
{% endhint %}

**Cement Extensions That Provide Controller Handlers**

* [Argparse](/extensions/argparse)

**API References:**

* [Cement Core Controller Module](https://cement.readthedocs.io/en/3.0/api/core/controller)
* [Cement Argparse Extension](https://cement.readthedocs.io/en/3.0/api/ext/ext_argparse)

## Application Base Controllers

When using application controllers there must be a single `base` controller responsible for handling [runtime dispatch](/terminology#runtime-dispatch). All other controllers are then [stacked](/terminology#controller-stacking) on top of the base controller (or other controllers already stacked on base). The base controller is the root of the application's command-line namespace.

{% hint style="info" %}
The initial base controller must have a `Controller.Meta.label` of `base` to designate it as the application's route of handing over runtime (argument parsing, mapping sub-commands to controllers, etc).

If no controller handler is registered with a `base` label, Cement will register a minimal controller in it's place that doesn't do anything other than allow extensions to stack properly.
{% endhint %}

{% tabs %}
{% tab title="Example: Defining an Application Base Controller" %}

```python
from cement import App, Controller, ex

class Base(Controller):
    class Meta:
        label = 'base'

    @ex(help='example sub-command')
    def cmd1(self):
        print('Inside Base.cmd1()')

class MyApp(App):
    class Meta:
        label = 'myapp'
        handlers = [
            Base,
        ]

with MyApp() as app:
    app.run()
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
usage: myapp [-h] [-d] [-q] {cmd1} ...

optional arguments:
  -h, --help   show this help message and exit
  -d, --debug  full application debug mode
  -q, --quiet  suppress all console output

sub-commands:
  {cmd1}
    cmd1       example sub-command

$ python myapp.py cmd1
Inside Base.cmd1()
```

{% endtab %}
{% endtabs %}

The above example demonstrates registering an application base controller. You will note in the `cli` tab that running `python myapp.py` without any arguments produces help output (same as if passing `--help`). This is the default action of the `ArgparseController`, but can be modified by overriding the `_default` method.

{% tabs %}
{% tab title="Example: Controller Default Method" %}

```python
from cement import App, Controller, ex

class Base(Controller):
    class Meta:
        label = 'base'

    def _default(self):
        print('Inside Base._default()')

    @ex(help='example sub-command')
    def cmd1(self):
        print('Inside Base.cmd1()')


class MyApp(App):
    class Meta:
        label = 'myapp'
        handlers = [
            Base,
        ]

with MyApp() as app:
    app.run()
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
Inside Base._default()
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
The `Controller._default` method is hidden from the command-line (ex: `--help` output), and does not require the `ex()` decorator to be active. You can modify the default method by setting it via `Controller.Meta.default_func`.
{% endhint %}

## Controller Arguments

Command line arguments defined by controllers are handled in two ways:

* Controller level
* Sub-command level

Controller level arguments are defined via `Controller.Meta.arguments` and are displayed/used at the top level of that controller, while sub-command level arguments are defined via the `ex()` decorator and only displayed and used under that sub-command namespace.

{% hint style="info" %}
Controller level arguments should be considered global, and relevant to the entire controller namespace. Sub-command level arguments are only relevant to that sub-command.
{% endhint %}

{% tabs %}
{% tab title="Example: Defining Controller Arguments" %}

```python
from cement import App, Controller, ex

class Base(Controller):
    class Meta:
        label = 'base'

        arguments = [
            ( [ '-f', '--foo' ],
              { 'help' : 'the notorious foo option',
                'action' : 'store',
                'dest' : 'foo', } ),
        ]

    @ex(
        help='example sub-command',
        arguments=[
            ( [ '--sub-option' ],
              { 'help' : 'option under sub-command',
                'action' : 'store_true',
                'dest' : 'sub_option' } ),
        ]
    )
    def cmd1(self):
        print('Inside Base.cmd1()')

        if self.app.pargs.foo is not None:
            print('Foo => %s' % self.app.pargs.foo)

        if self.app.pargs.sub_option is True:
            print('Sub Option Was Passed')


class MyApp(App):
    class Meta:
        label = 'myapp'
        handlers = [
            Base,
        ]

with MyApp() as app:
    app.run()
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py --help
usage: myapp [-h] [-d] [-q] [-f FOO] {cmd1} ...

optional arguments:
  -h, --help         show this help message and exit
  -d, --debug        full application debug mode
  -q, --quiet        suppress all console output
  -f FOO, --foo FOO  the notorious foo option

sub-commands:
  {cmd1}
    cmd1             example sub-command


$ python myapp.py cmd1 --help
usage: myapp cmd1 [-h] [--sub-option]

optional arguments:
  -h, --help    show this help message and exit
  --sub-option  option under sub-command


$ python myapp.py -f bar cmd1 --sub-option
Inside Base.cmd1()
Foo => bar
Sub Option Was Passed
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
How and where arguments are defined determines how they are used. An argument defined under a controller must be passed before any sub-command namespaces, otherwise the sub-parser will not recognize it and result in an `unrecognized argument error`.
{% endhint %}

## Processing Controller Level Arguments

In the above example we demonstrated accessing the controller level argument via `app.pargs.foo` in the `Base.cmd1()` method/sub-command. This worked fine. However, because controller level arguments should be considered global to the entire namespace, we should reduce duplicate code and handle controller level argument parsing in one place, regardless of what sub-command is passed.

The `ArgparseController` defines both a `_pre_argument_parsing` and`_post_argument_parsing` method for providing direct access to that controller's sub-parser (`self._parser`) and processing arguments. This is very similar to the `pre_argument_parsing` and `post_argument_parsing` [framework hooks](/core-foundation/hooks#cement-framework-hooks), but local in scope to the controller.

{% tabs %}
{% tab title="Example: Processing Controller Level Arguments" %}

```python
from cement import App, Controller, ex

class Base(Controller):
    class Meta:
        label = 'base'

        arguments = [
            ( [ '-f', '--foo' ],
              { 'help' : 'the notorious foo option',
                'action' : 'store',
                'dest' : 'foo', } ),
        ]

    def _post_argument_parsing(self):
        if self.app.pargs.foo is not None:
            print('Foo => %s' % self.app.pargs.foo)

    @ex(help='example sub-command')
    def cmd1(self):
        print('Inside Base.cmd1()')

    @ex(help='another example sub-command')
    def cmd2(self):
        print('Inside Base.cmd2()')


class MyApp(App):
    class Meta:
        label = 'myapp'
        handlers = [
            Base,
        ]

with MyApp() as app:
    app.run()
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py -f bar cmd1
Foo => bar
Inside Base.cmd1()

$ python myapp.py -f bar cmd2
Foo => bar
Inside Base.cmd2()
```

{% endtab %}
{% endtabs %}

## Additional Controllers and Namespaces

Any number of additional controllers can be added to your application after a base controller is registered. Additionally, these controllers can be `stacked` onto the base controller (or any other controller) in one of two ways:

* `embedded` - The controllers commands and arguments are included under the parent controller's name space.
* `nested` - The controller label is added as a sub-command under the parent controller's namespace (effectively this is a sub-command with additional sub-sub-commands under it)

For example, the `base` controller is accessed when calling `myapp.py` directly. Any commands under the `base` controller would be accessible as `myapp.py <cmd1>`, or `myapp.py <cmd2>`, etc. An `embedded` controller will merge its commands and options into the `base` controller namespace and appear to be part of the base controller... meaning you would still access the `embedded` controllers commands as `myapp.py <embedded_cmd1>`, etc (same for options).

For `nested` controllers, a prefix will be created with that controller's label under its parent's namespace. Therefore you would access that controller's commands and options as `myapp.py <controller_label> <controller_cmd1>`.

{% tabs %}
{% tab title="Example: Multiple Stacked Controllers" %}

```python
from cement import App, Controller, ex

class Base(Controller):
    class Meta:
        label = 'base'

    @ex(help='example sub-command')
    def cmd1(self):
        print('Inside Base.cmd1()')

class Embedded(Controller):
    class Meta:
        label = 'embedded'
        stacked_on = 'base'
        stacked_type = 'embedded'

    @ex(help='embedded sub-command')
    def cmd2(self):
        print('Inside Embedded.cmd2()')

class Nested(Controller):
    class Meta:
        label = 'nested'
        stacked_on = 'base'
        stacked_type = 'nested'

    @ex(help='nested sub-command')
    def cmd3(self):
        print('Inside Nested.cmd3()')

class MyApp(App):
    class Meta:
        label = 'myapp'
        handlers = [
            Base,
            Embedded,
            Nested,
        ]

with MyApp() as app:
    app.run()
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py  --help
usage: myapp [-h] [-d] [-q] {nested,cmd1,cmd2} ...

optional arguments:
  -h, --help          show this help message and exit
  -d, --debug         full application debug mode
  -q, --quiet         suppress all console output

sub-commands:
  {nested,cmd1,cmd2}
    nested            nested controller
    cmd1              example sub-command
    cmd2              embedded sub-command


$ python myapp.py cmd1
Inside Base.cmd1()


$ python myapp.py cmd2
Inside Embedded.cmd2()


$ python myapp.py nested cmd3
Inside Nested.cmd3()
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Controllers can be stacked on other controllers as many levels deep as necessary. An `embedded` controller can be stacked on top of a `nested` controller, and vice versa. There is little, if any, limitation.
{% endhint %}


# Output Rendering

## Introduction to the Output Interface

Cement defines an [Output Interface](https://cement.readthedocs.io/en/3.0/api/core/output/#cement.core.output.OutputInterface), as well as the default [DummyOutputHandler](https://docs.builtoncement.com/%7B%7B%20version%20%7D%7D/api/ext/ext_dummy.html) that implements the interface as a placeholder but does not actually produce any output.

{% hint style="warning" %}
Cement often includes multiple handler implementations of an interface that may or may not have additional features or functionality than the interface requires. The documentation below only references usage based on the interface and default handler (not the full capabilities of an implementation).
{% endhint %}

**Cement Extensions That Provide Output Handlers:**

* [Dummy](/extensions/dummy)
* [Json](/extensions/json)
* [Yaml](/extensions/yaml)
* [Jinja2](/extensions/jinja2)
* [Mustache](/extensions/mustache)
* [Tabulate](/extensions/tabulate)

**API References:**

* [Cement Core Output Module](https://cement.readthedocs.io/en/3.0/api/core/output)

## **Configuration**

### **Application Meta Options**

The following options under [`App.Meta`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta) modify configuration handling:

| **Option**          | **Description**                                   |
| ------------------- | ------------------------------------------------- |
| **output\_handler** | The handler that implements the output interface. |

## Rending Output

Cement applications do not need to use an output handler by any means. Most small applications can get away with simple `print()` statements. However, anyone who has ever built a bigger application that produces a lot of output will know that this can get ugly very quickly in your code.

Using an output handler allows the developer to keep their logic clean, and offload the display of relevant data to an output handler, possibly by templates or other means (GUI?).

An output handler has a `render()` function that takes a data dictionary to produce output. Some output handlers may also accept a `template` or other parameters that define how output is rendered. This is easily accessible by the application object.

{% tabs %}
{% tab title="Example: Rendering Output" %}

```python
from cement import App

with App('myapp' as app:
    app.run()

    # create a data dictionary
    data = {
        'foo': 'bar',
    }

    # render data dictionary
    app.render(data)
```

{% endtab %}
{% endtabs %}

The above example uses the default `dummy` output handler, therefore nothing is displayed on screen. That said, for an example we can use the JSonOutputHandler to see something happen:

{% tabs %}
{% tab title="Example: Defining an Output Handler" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['json']
        output_handler = 'json'

with MyApp() as app:
    app.run()

    # create a data dictionary
    data = {
        'foo': 'bar',
    }

    # render data dictionary
    app.render(data)
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
{"foo": "bar"}
```

{% endtab %}
{% endtabs %}

## Rendering Output via Templates

While some output handlers only require the `data` dictionary, others can utilize text templates to render formatted output to console.

{% tabs %}
{% tab title="Example: Rendering Output via Templates" %}
{% code title="myapp.py" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['jinja2']
        output_handler = 'jinja2'
        template_dir = './templates'

with MyApp() as app:
    app.run()

    # create a data dictionary
    data = {
        'foo': 'bar',
    }

    # render data dictionary
    app.render(data, 'example.jinja2')
```

{% endcode %}

{% code title="templates/example.jinja2" %}

```
Example Jinja2 Template

{% if foo %}
    Foo => {{ foo }}
{% endif %}
```

{% endcode %}
{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
Example Jinja2 Template

    Foo => bar
```

{% endtab %}
{% endtabs %}

## Template Directory Loading

Template directories are looked for in the most common places by default as defined by [`App.Meta.template_dirs`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.template_dirs):

* \~/.myapp/templates
* \~/.config/myapp/templates
* /usr/lib/myapp/templates

{% hint style="info" %}
End-users can prepend their own paths to this list by setting the `template_dir` setting under the application configuration settings.
{% endhint %}

Once a template is found, loading stops and the template is rendered.

## Creating an Output Handler

All interfaces in Cement can be overridden with your own implementation. This can be done either by sub-classing [`OutputHandler`](https://cement.readthedocs.io/en/3.0/api/core/output/#cement.core.output.OutputHandler) itself, or by sub-classing an existing extension's handlers in order to alter their functionality.

{% tabs %}
{% tab title="Example: Creating an Output Handler" %}
{% code title="myapp.py" %}

```python
from cement import App
from cement.core.output import OutputHandler

class MyOutputHandler(OutputHandler):
    class Meta:
        label = 'my_output_handler'

    # do something to implement the interface

class MyApp(App):
    class Meta:
        label = 'myapp'
        output_handler = 'my_output_handler'
        handlers = [
            MyOutputHandler,
        ]
```

{% endcode %}
{% endtab %}
{% endtabs %}


# Caching

## Introduction to the Cache Interface

Cement defines a [Cache Interface](https://cement.readthedocs.io/en/3.0/api/core/cache/#cement.core.cache.CacheInterface), but does not implement caching by default.

{% hint style="warning" %}
Cement often includes multiple handler implementations of an interface that may or may not have additional features or functionality than the interface requires. The documentation below only references usage based on the interface and default handler (not the full capabilities of an implementation).
{% endhint %}

**Cement Extensions That Provide Cache Handlers:**

* [Memcached](/extensions/memcached)
* [Redis](/extensions/redis)

**API References:**

* [Cement Core Cache Module](https://cement.readthedocs.io/en/3.0/api/core/cache)

## **Configuration**

### **Application Meta Options**

The following options under [`App.Meta`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta) modify configuration handling:

| **Option**         | **Description**                                  |
| ------------------ | ------------------------------------------------ |
| **cache\_handler** | The handler that implements the cache interface. |

## Working with Caches

The following example uses the [Memcached Extension](/extensions/memcached), which requires the `pylibmc` library to be installed, as well as a Memcached server running on `localhost:11211`.

{% tabs %}
{% tab title="Example: Working with Caches" %}

```python
from cement import App
from cement.utils.misc import init_defaults

CONFIG = init_defaults('myapp', 'memcached')
CONFIG['cache.memcached']['expire_time'] = 300 # seconds
CONFIG['cache.memcached']['hosts'] = ['127.0.0.1']

class MyApp(App):
    class Meta:
        label = 'myapp'
        config_defaults = CONFIG
        extensions = ['memcached']
        cache_handler = 'memcached'

with MyApp() as app:
    # Run the app
    app.run()

    # Set a cached value
    app.cache.set('my_key', 'my value')

    # Get a cached value
    app.cache.get('my_key')

    # Delete a cached value
    app.cache.delete('my_key')

    # Delete the entire cache
    app.cache.purge()
```

{% endtab %}
{% endtabs %}

## Creating a Cache Handler

All interfaces in Cement can be overridden with your own implementation. This can be done either by sub-classing [`CacheHandler`](https://cement.readthedocs.io/en/3.0/api/core/cache/#cement.core.cache.CacheHandler) itself, or by sub-classing an existing extension's handlers in order to alter their functionality.

{% tabs %}
{% tab title="Example: Creating a Cache Handler" %}
{% code title="myapp.py" %}

```python
from cement import App
from cement.core.cache import CacheHandler

class MyCacheHandler(CacheHandler):
    class Meta:
        label = 'my_cache_handler'

    # do something to implement the interface

class MyApp(App):
    class Meta:
        label = 'myapp'
        cache_handler = 'my_cache_handler'
        handlers = [
            MyCacheHandler,
        ]
```

{% endcode %}
{% endtab %}
{% endtabs %}


# Mail Messaging

## Introduction to the Mail Interface

Cement defines a [Mail Interface](https://cement.readthedocs.io/en/3.0/api/core/mail/#cement.core.mail.MailInterface), as well as the default [DummyMailHandler](https://docs.builtoncement.com/%7B%7B%20version%20%7D%7D/api/ext/ext_dummy.html#cement.ext.ext_dummy.DummyMailHandler) that implements the interface as a placeholder but does not actually send any mail.

{% hint style="warning" %}
Cement often includes multiple handler implementations of an interface that may or may not have additional features or functionality than the interface requires. The documentation below only references usage based on the interface and default handler (not the full capabilities of an implementation).
{% endhint %}

**Cement Extensions that Provide Mail Handlers:**

* [Dummy](/extensions/dummy) *(default)*
* [SMTP](/extensions/smtp)

**API References:**

* [Cement Core Mail Module](https://cement.readthedocs.io/en/3.0/api/core/mail)

## **Configuration**

### **Application Meta Options**

The following options under [`App.Meta`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta) modify configuration handling:

| **Option**        | **Description**                                 |
| ----------------- | ----------------------------------------------- |
| **mail\_handler** | The handler that implements the mail interface. |

## Working with Mail Messages

{% tabs %}
{% tab title="Example: Working with Mail Messages" %}

```python
from cement import App

with App('myapp') as app:
    app.run()

    # send a message using the defined mail handler
    app.mail.send("Test mail message",
                  subject='My Subject',
                  to=['me@example.com'],
                  from_addr='noreply@localhost',
                  )
```

{% endtab %}

{% tab title="cli" %}

```
python myapp.py

=============================================================================
DUMMY MAIL MESSAGE
-----------------------------------------------------------------------------

To: me@example.com
From: noreply@localhost
CC:
BCC:
Subject: My Subject

---

Test mail message

-----------------------------------------------------------------------------
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
The default `dummy` mail handler simply prints the message to console, and does not send anything. You can override the mail handler via `App.Meta.mail_handler`, for example using the [SMTP Extension](/extensions/smtp).
{% endhint %}

## Creating a Mail Handler

All interfaces in Cement can be overridden with your own implementation. This can be done either by sub-classing [`MailHandler`](https://cement.readthedocs.io/en/3.0/api/core/mail/#cement.core.mail.MailHandler) itself, or by sub-classing an existing extension's handlers in order to alter their functionality.

{% tabs %}
{% tab title="Example: Creating a Mail Handler" %}
{% code title="myapp.py" %}

```python
from cement import App
from cement.core.mail import MailHandler

class MyMailHandler(MailHandler):
    class Meta:
        label = 'my_mail_handler'

    # do something to implement the interface

class MyApp(App):
    class Meta:
        label = 'myapp'
        mail_handler = 'my_mail_handler'
        handlers = [
            MyMailHandler,
        ]
```

{% endcode %}
{% endtab %}
{% endtabs %}


# Framework Extensions

## Introduction to the Extension Interface

Cement defines an [Extension Interface](https://cement.readthedocs.io/en/3.0/api/core/extension/#cement.core.extension.ExtensionInterface), as well as the default [CementExtensionHandler](https://cement.readthedocs.io/en/3.0/api/core/extension/#cement.core.extension.ExtensionHandler) that implements the interface. Its purpose is to manage loading framework extensions and making them usable by the application. Extensions are similar to [Application Plugins](/core-foundation/plugins), but at the framework level (application agnostic).

{% hint style="warning" %}
Cement often includes multiple handler implementations of an interface that may or may not have additional features or functionality than the interface requires. The documentation below only references usage based on the interface and default handler (not the full capabilities of an implementation).
{% endhint %}

{% hint style="info" %}
As of Cement 2.1.3, optional extensions with external dependencies are now being shipped along with mainline sources. This means that although Cement Core continues to maintain a 100% zero dependency policy, Framework Extensions *can* rely on external deps. It is the responsibility of the application developer to include these dependencies in their application (as the Cement package does not include these dependencies).
{% endhint %}

**API References:**

* [Cement Core Extension Module](https://cement.readthedocs.io/en/3.0/api/core/extension)

## Configuration

### Application Meta Options

The following options under [`App.Meta`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta) modify extension handling:

| **Option**             | **Description**                                                                                                                                                                                                                                                                                           |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **extension\_handler** | A handler class that implements the Extension Interface.  This can be a string (label of a registered handler), an uninstantiated class, or an instantiated class object.  Default: [`ExtensionHandler`](https://cement.readthedocs.io/en/3.0/api/core/extension/#cement.core.extension.ExtensionHandler) |
| **extensions**         | A list of additional framework extensions to load.  Will be merged together with [`App.Meta.core_extensions`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.core_extensions).                                                                                 |

## Working with Extensions

In general, extensions are only loaded and accessed by the framework. That said the extension handler can be used to access information about loaded extensions, as well as manually load extensions if necessary.

{% tabs %}
{% tab title="Example: Working with Extensions" %}

```python
from cement import App

with App('myapp') as app:
    # list loaded extensions
    app.ext.list()

    # load an extension
    app.ext.load_extension('myapp.ext.myextension')

    # load a list of extensions
    app.ext.load_extensions(['myapp.ext.ext1',
                             'myapp.ext.ext2'])
```

{% endtab %}
{% endtabs %}

## Creating an Extension

The extension system is a mechanism for dynamically loading code to extend the functionality of the framework. In general, this includes the registration of interfaces, handlers, and/or hooks but can include controllers, command-line options, or anything else.

The preferred method of creating an extension would be via the included [developer tools](/getting-started/developer-tools):

```
$ cement generate extension /path/to/myapp/ext
```

This would produce something like the following:

{% tabs %}
{% tab title="Example: Creating an Extension" %}
{% code title="myapp/ext/ext\_myextension.py" %}

```python
from cement import minimal_logger

LOG = minimal_logger(__name__)

def myextension_pre_run_hook(app):
    # do something with app
    LOG.debug('Inside myextension_pre_run_hook!')

def load(app):
    # do something to extend cement
    app.hook.register('pre_run', myextension_pre_run_hook)
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
Extensions can provide anything from defining interfaces, registering hooks, or even adding command line arguments. The only thing required to make up an extension is the `load()` function.
{% endhint %}

You will notice that extensions are essentially the same as application plugins. The difference is found both in when/how the code is loaded, as well as the purpose of that code.

{% hint style="info" %}
Framework extensions add functionality **to the framework** for the application to utilize, whereas application plugins **extend the functionality of the application** itself.
{% endhint %}

## Loading Extensions

Extensions are loaded when [`App.setup()`](http://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.setup) is called on an application. Cement automatically loads all extensions listed under the application's [`App.Meta.core_extensions`](http://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.core_extensions) and [`App.Meta.extensions`](http://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.extensions) meta options.

To load the above example into our application, we just add it to the list of `App.Meta.extensions`. Let's assume the extension code lives in `myapp/ext/ext_myextension.py`:

{% tabs %}
{% tab title="Example: Loading Extensions" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = 'myapp.ext.ext_myextension'
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Note that Cement provides a shortcut for its own builtin extensions so that you can refer to extensions via their short name (ex: `json` instead of `cement.ext.ext_json`). All other extensions must be referenced by their full dotted Python module name.
{% endhint %}

## Loading Extensions via a Configuration File

Some use cases may require that end-users be able to modify what framework extensions are loaded depending on the needs of the application, while most extensions are defined by the developer to support key features.

The following example demonstrates an application loading extensions defined via the `extensions` setting under the application's configuration settings.

{% tabs %}
{% tab title="Example: Loading Extensions via Configuration File" %}
{% code title="myapp.py" %}

```python
from cement import App

with App('myapp') as app:
    app.run()

    for e in app.extension.list():
        print(e)
```

{% endcode %}

{% code title="\~/.myapp.conf" %}

```
[myapp]
exensions = json, yaml, myapp.ext.ext_myextension
```

{% endcode %}
{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
cement.ext.ext_dummy
cement.ext.ext_smtp
cement.ext.ext_plugin
cement.ext.ext_configparser
cement.ext.ext_logging
cement.ext.ext_argparse
cement.ext.ext_json
cement.ext.ext_yaml
myapp.ext.ext_myextension
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
Note that extensions loaded in this way will happen **after** the config handler is setup. Normally, extensions are loaded just before the configuration files are read. Therefore, some extensions may not be compatible with this method if they attempt to perform any actions before `app.setup()` completes (such as in early framework hooks before configuration files are loaded).
{% endhint %}


# Application Plugins

## Introduction to the Plugin Interface

Cement defines a Plugin Interface, as well as the default [CementPluginHandler](https://cement.readthedocs.io/en/3.0/api/ext/ext_plugin/#cement.ext.ext_plugin.CementPluginHandler) that implements the interface.

{% hint style="warning" %}
Cement often includes multiple handler implementations of an interface that may or may not have additional features or functionality than the interface requires. The documentation below only references usage based on the interface and default handler (not the full capabilities of an implementation).
{% endhint %}

**Cement Extensions that Provide Plugin Handlers:**

* [Plugin](/extensions/plugin)

**API References:**

* [Cement Core Plugin Module](https://cement.readthedocs.io/en/3.0/api/core/plugin/)

## Configuration

### Application Configuration Settings

The following settings under the application's primary configuration section modify plugin handling:

| **Setting**     | **Description**                                                                                   |
| --------------- | ------------------------------------------------------------------------------------------------- |
| **plugin\_dir** | A directory path where plugin code can be found.  Will be **prepended** to `App.Meta.plugin_dirs` |

### Application Meta Options:

The following options under [`App.Meta`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta) modify plugin handling:

| **Option**         | **Description**                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **plugins**        | A *hardcoded* list of plugins to load.  In general, application plugins should be dynamically enabled/disabled via the application's configuration files.  However, some application designs may prefer to always load specific builtin plugins. Default: `[]`                                                                                                                                                                                               |
| **config\_dirs**   | Plugin configuration files are loaded from any discovered application configuration directories.                                                                                                                                                                                                                                                                                                                                                             |
| **plugin\_module** | A python module (dotted import path) where plugin code can be loaded from instead of external directories (builtin plugins shipped with the application code).  Default: `myapp.plugins`                                                                                                                                                                                                                                                                     |
| **plugin\_dirs**   | A list of directory paths where plugin code (modules) can be loaded from (external to the application).  Will be merged with [`App.Meta.core_system_plugin_dirs`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.core_system_plugin_dirs) and [`App.Meta.core_user_plugin_dirs`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.core_user_plugin_dirs).  Default: `[]` |

## Working with Plugins

The plugin handler can be used to access information about loaded plugins, as well as manually loading plugins if necessary.

{% tabs %}
{% tab title="Example: Working with Extensions" %}

```python
from cement import App

with App('myapp') as app:
    # list loaded plugins
    app.plugin.get_loaded_plugins()

    # list enabled plugins
    app.plugin.get_enabled_plugins()

    # list disabled plugins
    app.plugin.get_disabled_plugins()

    # load a plugin
    app.plugin.load_plugin('myplugin')

    # load a list of plugins
    app.plugin.load_plugins(['myplugin1',
                             'myplugin2'])
```

{% endtab %}
{% endtabs %}

## Creating a Plugin

The plugin system is a mechanism for dynamically loading code to extend the functionality of a specific application. In general, this includes the registration of interfaces, handlers, and/or hooks but can include controllers, command-line options, or anything else.

The preferred method of creating a plugin would be via the included [developer tools](/getting-started/developer-tools):

```
$ cement generate plugin /path/to/myapp/plugins
```

This will produce an example plugin directory like the following:

```
├── __init__.py
├── controllers
│   ├── __init__.py
│   └── myplugin.py
└── templates
    ├── __init__.py
    └── plugins
        └── myplugin
            └── command1.jinja2
```

The example plugin includes a controller, sub-command, and output generated via [Jinja2](/extensions/jinja2) template. That said, the only thing Cement needs is a `load()` function.... everything else is arbitrary. In the generated plugin, we find this in `myplugin/__init__.py`:

```python
import os
from .controllers.myplugin import MyPlugin

def add_template_dir(app):
    path = os.path.join(os.path.dirname(__file__), 'templates')
    app.add_template_dir(path)

def load(app):
    app.handler.register(MyPlugin)
    app.hook.register('post_setup', add_template_dir)
```

{% hint style="info" %}
Plugins can provide anything from defining interfaces, registering hooks, or even adding command line sub-commands and arguments. The only thing required to make up a plugin is a `load()` function in `myplugin.py` or `myplugin/__init__.py` files.
{% endhint %}

You will notice that plugins are essentially the same as framework extensions. The difference is found both in when/how the code is loaded, as well as the purpose of that code.

{% hint style="info" %}
Framework extensions add functionality **to the framework** for the application to utilize, whereas application plugins **extend the functionality of the application** itself.
{% endhint %}

## Loading a Plugin

Plugin modules are discovered and loaded in the following order:

* From directories listed in `App.Meta.plugin_dirs`
* From the python path defined in `App.Meta.plugin_module`

In order for the framework to know about a plugin, it must be defined in the application's configuration settings under its designated section of `plugin.myplugin`. This configuration block can live in any application configuration file, including files loaded from configuration dirs (ex: `/etc/myapp/plugin.d/myplugin.conf`).

{% tabs %}
{% tab title="Example: Loading a Plugin" %}
{% code title="myapp.py" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        plugin_dirs = ['./plugins']

with MyApp() as app:
    app.run()
```

{% endcode %}

{% code title="plugins/myplugin.py" %}

```python
def load(app):
    print('Inside MyPlugin!')
```

{% endcode %}
{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
Inside MyPlugin!
...
```

{% endtab %}
{% endtabs %}

If a plugin configuration is found, its settings will be loaded into the app. However, the plugin will only be loaded if it is enabled:

```
[myapp]
# ...

[plugin.myplugin]
enabled: true
```

## Single File Plugins vs. Plugin Directories

As of Cement 2.9.x, plugins can be either a single file (i.e `myplugin.py`) or a python module directory (i.e. `myplugin/__init__.py`). Both will be loaded and executed the exact same way.

One caveat, however, is that the submodules referenced from within a plugin directory must be relative paths. For example:

{% tabs %}
{% tab title="Example: Loading Submodules in a Plugin" %}
{% code title="myplugin/**init**.py" %}

```python
from .controllers import MyPluginController

def load(app):
    app.handler.register(MyPluginController)
```

{% endcode %}
{% endtab %}
{% endtabs %}

This will ensure that Python will properly load the sub-modules regardless of where they live on the filesystem (or within a project's own modules, etc).

## Loading Templates From Plugin Directories

In order for a plugin to use its own template files, its templates directory first needs to be registered with the app. We accomplish this with a `post_setup` hook:

{% tabs %}
{% tab title="Example: Registering Plugin Template Directories" %}
{% code title="myplugin/**init**.py" %}

```python
import os

def add_template_dir(app):
    path = os.path.join(os.path.basename(self.__file__, 'templates')
    app.add_template_dir(path)

​def load(app):
    app.hook.register('post_setup', add_template_dir)
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Creating a Plugin Handler

All interfaces in Cement can be overridden with your own implementation. This can be done either by sub-classing [`PluginHandler`](https://cement.readthedocs.io/en/3.0/api/core/plugin/#cement.core.plugin.PluginHandler) itself, or by sub-classing an existing extension's handlers in order to alter their functionality.

{% tabs %}
{% tab title="Example: Creating a Plugin Handler" %}
{% code title="myapp.py" %}

```python
from cement import App
from cement.core.plugin import PluginHandler

class MyPluginHandler(PluginHandler):
    class Meta:
        label = 'my_plugin_handler'

    # do something to implement the interface

class MyApp(App):
    class Meta:
        label = 'myapp'
        plugin_handler = 'my_plugin_handler'
        handlers = [
            MyPluginHandler,
        ]
```

{% endcode %}
{% endtab %}
{% endtabs %}


# Templating

## Introduction to the Template Interface <a href="#introduction-to-the-output-interface" id="introduction-to-the-output-interface"></a>

Cement defines a [Template Interface](https://cement.readthedocs.io/en/3.0/api/core/template/#cement.core.template.TemplateInterface), as well as a default [`DummyTemplateHandler`](https://cement.readthedocs.io/en/3.0/api/ext/ext_dummy/#cement.ext.ext_dummy.DummyTemplateHandler) that implements the interface as a placeholder but does not actually do anything.

{% hint style="warning" %}
Cement often includes multiple handler implementations of an interface that may or may not have additional features or functionality than the interface requires. The documentation below only references usage based on the interface and default handler (not the full capabilities of an implementation).
{% endhint %}

\*\*\*\*

**Cement Extensions That Provide Template Handlers:**

* ​[Jinja2](/extensions/jinja2)
* [Mustache](/extensions/mustache)
* [Dummy](/extensions/dummy)

**API References:**

* [​Cement Core Template Module​](https://cement.readthedocs.io/en/3.0/api/core/template)

## **Configuration** <a href="#configuration" id="configuration"></a>

### **Application Meta Options** <a href="#application-meta-options" id="application-meta-options"></a>

The following options under [`App.Meta`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta) modify configuration handling:

| **Option**            | **Description**                                     |
| --------------------- | --------------------------------------------------- |
| **template\_handler** | The handler that implements the template interface. |

## Working with Templates

The template handler can be used to render content in-line, as well as copy render source directories before copying them to their destination.

{% tabs %}
{% tab title="Example: Working with Templates" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['jinja2']
        template_handler = 'jinja2'

with MyApp() as app:
    # create a data dictionary for templating
    data = {
        'foo': 'bar'
    }

    # render content as template
    app.template.render('Foo => {{ foo }}', data)

    # render and copy a source directory
    src = '/path/to/source/dir'
    dst = '/path/to/destination/dir'
    app.template.copy(src, dst, data)
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
When copying a source directory, both the file/directory path names themselves are rendered as templates as well as the contents of files.
{% endhint %}

## Creating a Template Handler

All interfaces in Cement can be overridden with your own implementation. This can be done either by sub-classing [`TemplateHandler`](https://cement.readthedocs.io/en/3.0/api/core/template/#cement.core.template.TemplateHandler) itself, or by sub-classing an existing extension's handlers in order to alter their functionality.

{% tabs %}
{% tab title="Example: Creating a Template Handler" %}
{% code title="myapp.py" %}

```python
from cement import App
from cement.core.template import TemplateHandler

class MyTemplateHandler(TemplateHandler):
    class Meta:
        label = 'my_template_handler'

    # do something to implement the interface

class MyApp(App):
    class Meta:
        label = 'myapp'
        template_handler = 'my_template_handler'
        handlers = [
            MyTemplateHandler,
        ]
```

{% endcode %}
{% endtab %}
{% endtabs %}


# Utilities


# Filesystem

## Introduction to the Filesystem Utilities <a href="#introduction-to-the-output-interface" id="introduction-to-the-output-interface"></a>

Cement includes a [Filesystem Utility Module](https://cement.readthedocs.io/en/3.0/api/utils/fs/) with helpers for common tasks related to filesystem management.

**API References:**

* [Cement Filesystem Utility Module](https://cement.readthedocs.io/en/3.0/api/utils/fs/)

## Temporary Directories and Files

Creating and cleaning up temporary directories and files can be tedious, so we created the [`fs.Tmp`](https://cement.readthedocs.io/en/3.0/api/utils/fs/#cement.utils.fs.Tmp) class to make management easy:

{% tabs %}
{% tab title="Example: Temporary Directories and Files" %}
{% code title="example.py" %}

```python
import os
from cement import fs

# create a tmp object (includes dir and file)
with fs.Tmp() as t:
    # do something with a temporary dir
    print('Temp Dir: %s' % t.dir)
    os.listdir(t.dir)

    # do something with a temporary file
    print('Temp File: %s' % t.file)
    with open(t.file, 'w') as f:
        f.write('some data')
```

{% endcode %}
{% endtab %}

{% tab title="cli" %}

```
$ python example.py
Temp Dir: /var/folders/jm/cr24ncsn1lgdblxm2mvgtdt40000gn/T/tmpwzo8kh89
Temp File: /var/folders/jm/cr24ncsn1lgdblxm2mvgtdt40000gn/T/tmps4s7n8xg
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
When using the Python `with` operator, the temporary directory and file are automatically cleaned up when exiting the block.
{% endhint %}

## Backup Directories and Files

Creating a `.bak` of a directory or file before modifying it is one of the most common tasks when working with the filesystem, but often takes some tedious code to do so without overwriting existing backups.  The [`fs.backup()`](https://cement.readthedocs.io/en/3.0/api/utils/fs/#cement.utils.fs.backup) creates a `.bak` file, or if it exists `.bak.0`, `.bak.1`, `.bak.2`, etc.

{% tabs %}
{% tab title="Example: Backup Directories and Files" %}

```python
from cement import fs

# create a backup of a file or directory
fs.backup('/path/to/my/file')
```

{% endtab %}
{% endtabs %}

## Filesystem Paths

Best practice when working with paths is to use `os.path.join()` to ensure cross-platform compatibility and also expanding the absolute path to account for things like `~` (user home dir) on Linux. We've created a number of helpers to meld these together for common tasks:

{% tabs %}
{% tab title="Example: Filesystem Paths" %}

```python
from cement import fs

# expand the full absolute path
fs.abspath('./some/relative/path')
fs.abspath('~/some/user/path/')

# join a path while also expanding absolute path
fs.join('~', '.myapp')
fs.join('.', 'some', 'sub-dir')

# join a path and test that it exists
path,exists = fs.join_exists('~', '.myapp')
if exists is True:
    # do something with the full absolute path
    os.listdir(path)

# ensure a directory exists
fs.ensure_dir_exists('/path/to/some/dir')

# ensure a parent directory exists
fs.ensure_parent_dir_exists('/path/to/parent/child')
```

{% endtab %}
{% endtabs %}


# Shell

## Introduction to the Shell Utilities <a href="#introduction-to-the-output-interface" id="introduction-to-the-output-interface"></a>

Cement includes a [Shell Utility Module](https://cement.readthedocs.io/en/3.0/api/utils/shell/) with helpers for common tasks related to executing commands, spawning subprocesses/threads, and other tasks.

**API References:**

* [Cement Shell Utility Module](https://cement.readthedocs.io/en/3.0/api/utils/shell/)

## Prompting User Input

Requesting input from the user is straight forward, however we've included the [`shell.Prompt`](https://cement.readthedocs.io/en/3.0/api/utils/shell/#cement.utils.shell.Prompt) utility to expand beyond just a simple one-dimensional input response.

{% tabs %}
{% tab title="Example: User Input Prompts" %}
{% code title="example.py" %}

```python
from cement import shell

### simple user response prompt

p = shell.Prompt("Press Enter To Continue", default='ENTER')
res = p.prompt()

### provide a numbered list for longer selections

p = shell.Prompt("Where do you live?",
                 options=[
                     'San Antonio, TX',
                     'Austin, TX',
                     'Dallas, TX',
                     'Houston, TX',
                 ],
                 numbered = True)
res = p.prompt()

### Create a more complex prompt, and process the input

class MyPrompt(shell.Prompt):
    class Meta:
        text = "Do you agree to the terms?"
        options = ['Yes', 'no', 'maybe-so']
        options_separator = '|'
        default = 'no'
        clear = True
        max_attempts = 99

    def process_input(self):
        if self.input.lower() == 'yes':
            # do something crazy
            pass
        else:
            # don't do anything... maybe exit?
            print("User doesn't agree! I'm outa here")

p = MyPrompt()
```

{% endcode %}
{% endtab %}

{% tab title="cli" %}

```
$ python example.py

### simple user response prompt

Press Enter To Continue

### provide a numbered list for longer selections

Where do you live?

1: San Antonio, TX
2: Austin, TX
3: Dallas, TX
4: Houston, TX

Enter the number for your selection: 1

### Create a more complex prompt, and process the input

Do you agree to the terms? [Yes|no|maybe-so] no
User doesn't agree! I'm outa here
```

{% endtab %}
{% endtabs %}

## Executing Commands

Shell commands can be executed via the `shell.cmd()` function in two ways; by capturing STDOUT/STDERR and exit code, or just the exit code and letting STDOUT/STDERR print to console normally.

{% tabs %}
{% tab title="Example: Executing Commands" %}

```python
from cement import shell

### execute command and capture output
out, err, code = shell.cmd('echo helloworld')

### execute command with output to console
code = shell.cmd('echo helloworld', capture=False)
```

{% endtab %}
{% endtabs %}

## Spawning Processes and Threads

Spawning processes and threads is easy via the `shell.spawn()` helper.

{% tabs %}
{% tab title="Example: Spawning Processes and Threads" %}

```python
from cement import shell

def add(a, b):
    print(a + b)

### spawn a process
p = shell.spawn(add, args=(12, 27))
p.join()

### spawn a thread
t = shell.spawn(add, args=(12, 27), thread=True)
t.join()
```

{% endtab %}
{% endtabs %}

See the [multiprocessing](https://docs.python.org/3/library/multiprocessing.html) and [threading](https://docs.python.org/3/library/threading.html) modules in the Python standard library for more information on working with processes and threads.


# Miscellaneous

## Introduction to the Miscellaneous Utilities <a href="#introduction-to-the-output-interface" id="introduction-to-the-output-interface"></a>

Cement includes a Miscellaneous Utilities Module with helpers for common tasks that don't fit anywhere on their own.

**API References:**

* [​Cement Misc Utility Module​](https://cement.readthedocs.io/en/3.0/api/utils/misc/)

## Initialize Default Dictionaries

The included [`misc.init_defaults()`](https://cement.readthedocs.io/en/3.0/api/utils/misc/#cement.utils.misc.init_defaults) is used to initialize a defaults dictionary for configuration settings and meta options.

{% tabs %}
{% tab title="Example: Initialize Default Dictionaries" %}

```python
from cement.utils.misc import init_defaults

# create a dict with nested dicts
CONFIG = init_defaults('myapp', 
                       'log.logging', 
                       'output.json')

# setup the nested dicts
CONFIG['myapp']['foo'] = 'bar'
CONFIG['log.logging']['level'] = 'INFO'
CONFIG['output.json']['overridable'] = True
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
The `init_defaults` helper simply generates a dict with nested dicts of the given keys. It does not do anything special, but is used throughout the documentation as it generally makes things more readable in examples.

You can always use a standard `dict` for configuration and meta defaults, which often makes more sense when building larger applications with a lot of default settings to manage.
{% endhint %}

## Testing True Values

When reading configuration files and other unknown data sources, we often need to convert strings to boolean. For example, a setting of `true` read from a configparser text based config file will be a `str` type, but we want it as an `bool`.

The [`misc.is_true()`](https://cement.readthedocs.io/en/3.0/api/utils/misc/#cement.utils.misc.is_true) helper converts common `true` values to boolean.

{% tabs %}
{% tab title="Example: Testing True Values" %}

```python
from cement.utils.misc import is_true

# testing true values
is_true(1)
is_true('1')
is_true('true')
is_true('True')
is_true('TRUE')
is_true('yes')
is_true('on')
is_true(True)


# testing false values
is_true(0)
is_true('0')
is_true('false')
is_true('False')
is_true('FALSE')
is_true('no')
is_true('off')
is_true(False)
```

{% endtab %}
{% endtabs %}

## Minimal Logging

Cement provides a [`misc.minimal_logger()`](https://cement.readthedocs.io/en/3.0/api/utils/misc/#cement.utils.misc.minimal_logger) helper for use outside of the `App` object, most notably for extensions (though they can use the application log also). This should only be used by the framework, or when the application log is not available (before application is setup maybe).

{% tabs %}
{% tab title="Example: Minimal Logging" %}

```python
from cement.utils.misc import minimal_logger
LOG = minimal_logger('logging-namespace')
LOG.debug('This is a debug message')
```

{% endtab %}
{% endtabs %}

## Random Strings

The [`misc.rando()`](https://cement.readthedocs.io/en/3.0/api/utils/misc/#cement.utils.misc.rando) helper is available when a random string is necessary, generally used for testing purposes.

{% tabs %}
{% tab title="Example: Random Strings" %}

```python
from cement.utils.misc import rando

# create a random string (md5)
rando()

# add a salt
rando('anchG45jJfka')
```

{% endtab %}
{% endtabs %}

## Limit Text Line Length

When working with command lines, keeping output lines to less than 78 characters is a good best-practice. Cement provides the [`misc.wrap()`](https://cement.readthedocs.io/en/3.0/api/utils/misc/#cement.utils.misc.wrap) helper to accomplish this by adding a line break `\n`

{% tabs %}
{% tab title="Example: Limit Text Line Length" %}

```python
from cement.utils.misc import wrap

long = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis blandit cursus eros eget dictum. Curabitur eleifend nunc id eros consequat, vitae convallis quam sollicitudin. Nunc vitae efficitur lorem. Quisque facilisis imperdiet sem, nec facilisis elit faucibus non. Cras vitae interdum orci. Donec rutrum diam eget leo tincidunt, quis feugiat neque fermentum. Cras vel velit nibh. Phasellus porttitor, diam vitae ornare malesuada, mauris nulla ornare tortor, id congue tellus justo vel urna. Quisque tincidunt quis enim a bibendum. Donec sagittis nulla eu elit sollicitudin consequat."

# wrap with default 77 characters
res = wrap(long)
print(res)

# wrap with a total of 50 characters, and break long words / hyphens
res = wrap(long, width=50, long_words=True, hyphens=True)
print(res)
```

{% endtab %}

{% tab title="cli" %}

```
$ python example.py

# default 77 characters

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis blandit cursus
eros eget dictum. Curabitur eleifend nunc id eros consequat, vitae convallis
quam sollicitudin. Nunc vitae efficitur lorem. Quisque facilisis imperdiet
sem, nec facilisis elit faucibus non. Cras vitae interdum orci. Donec rutrum
diam eget leo tincidunt, quis feugiat neque fermentum. Cras vel velit nibh.
Phasellus porttitor, diam vitae ornare malesuada, mauris nulla ornare tortor,
id congue tellus justo vel urna. Quisque tincidunt quis enim a bibendum.

# 50 characters and wrap long words or hyphens

Donec sagittis nulla eu elit sollicitudin consequat.
Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Duis blandit cursus eros eget dictum.
Curabitur eleifend nunc id eros consequat, vitae
convallis quam sollicitudin. Nunc vitae efficitur
lorem. Quisque facilisis imperdiet sem, nec
facilisis elit faucibus non. Cras vitae interdum
orci. Donec rutrum diam eget leo tincidunt, quis
feugiat neque fermentum. Cras vel velit nibh.
Phasellus porttitor, diam vitae ornare malesuada,
mauris nulla ornare tortor, id congue tellus justo
vel urna. Quisque tincidunt quis enim a bibendum.
Donec sagittis nulla eu elit sollicitudin
consequat.
```

{% endtab %}
{% endtabs %}


# Extensions


# Alarm

## Introduction

The Alarm Extension provides the [AlarmManager](http://cement.readthedocs.io/en/3.0/api/ext/ext_alarm/#cement.ext.ext_alarm.AlarmManager) extended object, with easy mechanisms for handling long running operations that might timeout after a set amount of time.

**API References:**

* [Cement Alarm Extension](http://cement.readthedocs.io/en/3.0/api/ext/ext_alarm/)
* [Python Signal Library](https://docs.python.org/3.5/library/signal.html)

## **Requirements**

* No external dependencies

{% hint style="info" %}
As of Cement 3.0.8, applications using optional extensions should include them in their dependencies for future compatibility in the event additional dependencies are required:

Ex: `cement[alarm]`
{% endhint %}

## Platform Support

* Unix
* Linux
* macOS (Darwin)

## **Configuration**

This extension does not rely on any application level configuration settings or meta options.

## **Usage**

{% tabs %}
{% tab title="Example: Using Alarm Extension" %}

```python
import time
from cement import App, CaughtSignal

class MyApp(App):
    class Meta:
        label = 'myapp'
        exit_on_close = True
        extensions = ['alarm']


with MyApp() as app:
    try:
        app.run()
        app.alarm.set(3, "The operation timed out after 3 seconds!")

        # do something that takes time to operate
        time.sleep(5)

        app.alarm.stop()

    except CaughtSignal as e:
        print(e.msg)
        app.exit_code = 1
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
ERROR: The operation timed out after 3 seconds!
Caught signal 14
```

{% endtab %}
{% endtabs %}


# Argparse

## Introduction

The Argparse Extension provides the [`ArgparseArgumentHandler`](http://cement.readthedocs.io/en/3.0/api/ext/ext_argparse/#cement.ext.ext_argparse.ArgparseArgumentHandler) for argument parsing, and the [`ArgparseController`](http://cement.readthedocs.io/en/3.0/api/ext/ext_argparse/#cement.ext.ext_argparse.ArgparseController) for runtime dispatch. Both are the defaults used by Cement.

**Documentation References:**

* [Arguments](/core-foundation/arguments)
* [Controllers](/core-foundation/controllers)

**API References**

* [Cement Argparse Extension](http://cement.readthedocs.io/en/3.0/api/ext/ext_argparse/)
* [Python Argparse Module](https://docs.python.org/3/library/argparse.html)

## Requirements

* No external dependencies

## Configuration

This extension does not rely on any application level configuration settings or meta options.

## Usage

The following is an example application using both the [`ArgparseArgumentHandler`](http://cement.readthedocs.io/en/3.0/api/ext/ext_argparse/#cement.ext.ext_argparse.ArgparseArgumentHandler) and [`ArgparseController`](http://cement.readthedocs.io/en/3.0/api/ext/ext_argparse/#cement.ext.ext_argparse.ArgparseController). Note that the default `arg_handler` is already set to`ArgparseArgumentHandler` by `App`.

{% tabs %}
{% tab title="Example: Using Argparse Extension" %}

```python
from cement import App, Controller, ex

class Base(Controller):
    class Meta:
        label = 'base'
        arguments = [
            (['--base-foo'],
             {'help': 'base foo option'}),
        ]

    @ex(hide=True)
    def default(self):
        print('Inside Base.default')

        if self.app.pargs.base_foo:
            # do something with self.app.pargs.base_foo
            print('Base Foo > %s' % self.app.pargs.base_foo)

    @ex(
        arguments=[
            (['--command1-opt'],
             {'help': 'option under command1',
              'action': 'store_true'})
        ],
        aliases=['cmd1'],
        help='sub-command under myapp base controller',
    )
    def command1(self):
        print('Inside Base.command1')

        if self.app.pargs.command1_opt:
            # do something with self.app.pargs.command1_opt
            pass

class Embedded(Controller):
    class Meta:
        label = 'embedded_controller'
        stacked_on = 'base'
        stacked_type = 'embedded'

    @expose(help="embedded under base controller")
    def command2(self):
        print('Inside Embedded.command2')

class Nested(Controller):
    class Meta:
        label = 'nested_controller'
        stacked_on = 'base'
        stacked_type = 'nested'
        arguments = [
            (['--nested-opt'],
             {'help': 'option under nested-controller'}),
        ]

    @expose(help="sub-command under nested-controller")
    def command3(self):
        print('Inside Nested.command3')

class MyApp(App):
    class Meta:
        label = 'myapp'
        handlers = [
            Base,
            Embedded,
            Nested,
        ]

with MyApp() as app:
    app.run()
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py --help
usage: myapp.py [-h] [--quiet] [--base-foo BASE_FOO]
                {nested-controller,command1,cmd1,default,command2} ...

optional arguments:
  -h, --help            show this help message and exit
  --quiet               suppress all output
  --base-foo BASE_FOO   base foo option

sub-commands:
  {nested-controller,command1,cmd1,default,command2}
    nested-controller   nested-controller controller
    command1 (cmd1)     command1 is a sub-command under base controller
    command2            command2 embedded under base controller


$ python myapp.py --base-foo bar
Inside Base.default
Base Foo > bar


$ python myapp.py command1 --help
usage: myapp.py command1 [-h] [--command1-opt]

optional arguments:
  -h, --help      show this help message and exit
  --command1-opt  option under command1


$ python myapp.py command1
Inside Base.command1


$ python myapp.py command2
Inside Embedded.command2


$ python myapp.py nested-controller --help
usage: myapp.py nested-controller [-h] [--nested-opt] {command3} ...

optional arguments:
  -h, --help            show this help message and exit
  --nested-opt          option under nested-controller

sub-commands:
  {command3}
    command3            command3 under nested-controller


$ python myapp.py nested-controller command3
Inside Nested.command3
```

{% endtab %}
{% endtabs %}


# Colorlog

## Introduction

The ColorLog Extension provides the [`ColorLogHandler`](http://cement.readthedocs.io/en/3.0/api/ext/ext_colorlog/#cement.ext.ext_colorlog.ColorLogHandler) for logging, and is a sub-class and drop-in replacement for the default log handler [`LoggingLogHandler`](http://cement.readthedocs.io/en/3.0/api/ext/ext_logging/#cement.ext.ext_logging.LoggingLogHandler).

**Documentation References:**

* [Logging](/core-foundation/logging-1)

**API References:**

* [Cement Colorlog Extension](http://cement.readthedocs.io/en/3.0/api/ext/ext_colorlog/)
* [Colorlog Module](https://pypi.org/project/colorlog/)

## Requirements

* Colorlog

{% hint style="info" %}
Cement 3.0.8+:

`pip install cement[colorlog]`
{% endhint %}

{% hint style="warning" %}
Applications using Cement <3.0.8 should continue to include `colorlog` in their dependencies.
{% endhint %}

## Installation

```
pip install cement[colorlog]
```

## Configuration

This handler honors the following settings under a `[log.colorlog]` section of the configuration:

| **Setting**                | **Description**                                                                                         |
| -------------------------- | ------------------------------------------------------------------------------------------------------- |
| **level**                  | The level to display logs for.  One of `INFO`, `WARNING`, `ERROR`, `FATAL`, `DEBUG`.  Default: `INFO`   |
| **file**                   | The filesystem path of the log file.  Default: `None`                                                   |
| **to\_console**            | Whether or not to log to console.  Default: `True`                                                      |
| **rotate**                 | Whether or not rotate the log file.  Default: `False`                                                   |
| **max\_bytes**             | Maximum file size (in bytes) until the log file is rotated (if rotation is enabled).  Default: *512000* |
| **max\_files**             | Maximum number of files to keep when rotating is enabled.  Default: `4`                                 |
| **colorize\_file\_log**    | Whether or not to colorize the log file.  Default: `False`                                              |
| **colorize\_console\_log** | Whether or not to colorize the console log.  Default: `True`                                            |

{% hint style="warning" %}
Note that there are precautions in place to disable colorized logging if the session is not a valid TTY via `sys.stdout.istty()`
{% endhint %}

A sample config section might look like:

{% code title="\~/.myapp.conf" %}

```
[log.colorlog]
file = /path/to/config/file
level = info
to_console = true
rotate = true
max_bytes = 512000
max_files = 4
colorize_file_log = false
colorize_console_log = true
```

{% endcode %}

## Usage

{% tabs %}
{% tab title="Example: Using Colorlog Extension" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['colorlog']
        log_handler = 'colorlog'

with MyApp() as app:
    app.run()
    app.log.debug('This is my debug message')
    app.log.info('This is my info message')
    app.log.warning('This is my warning message')
    app.log.error('This is my error message')
    app.log.fatal('This is my critical message')
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
The colors can be customized by passing in a `colors` dictionary mapping overriding the [`ColorLogHandler.Meta.colors`](http://cement.readthedocs.io/en/3.0/api/ext/ext_colorlog/#cement.ext.ext_colorlog.ColorLogHandler.Meta.colors) option
{% endhint %}

{% tabs %}
{% tab title="Example: Customizing Colorlog Colors" %}

```python
from cement import App, init_defaults

META = init_defaults('log.colorlog')
META['log.colorlog']['colors'] = {
    'DEBUG':    'cyan',
    'INFO':     'green',
    'WARNING':  'yellow',
    'ERROR':    'red',
    'CRITICAL': 'red,bg_white',
}

class MyApp(App):
    class Meta:
        label = 'myapp'
        extension = ['colorlog']
        log_handler = 'colorlog'
        meta_defaults = META
```

{% endtab %}
{% endtabs %}


# ConfigParser

## Introduction

The ConfigParser Extension provides the [ConfigParserConfigHandler](https://cement.readthedocs.io/en/3.0/api/ext/ext_configparser/#cement.ext.ext_configparser.ConfigParserConfigHandler) for configuration files and settings, and is the default configuration handler used by Cement.

**Documentation References:**

* [Configuration Settings](/core-foundation/configuration-settings)

**API References:**

* [Cement ConfigParser Extension](http://cement.readthedocs.io/en/3.0/api/ext/ext_configparser/)
* [Python ConfigParser Module](https://docs.python.org/3/library/configparser.html)

## Requirements

* No external dependencies

## Configuration

This extension does not rely on any application level configuration settings or meta options.

## Usage

See the [Configuration Settings](/core-foundation/configuration-settings) documentation.


# Daemon

## Introduction

The Daemon Extension enables applications to easily perform standard daemonization operations.

**Features**

* Configurable runtime user and group
* Adds the `--daemon` command line option
* Add `app.daemonize()` function to trigger daemon functionality where necessary (either in a cement `pre_run` hook or an application controller sub-command, etc)
* Manages a PID file including cleanup on `app.close()`

**API References:**

* [Cement Daemon Extension](https://cement.readthedocs.io/en/3.0/api/ext/ext_daemon/)

## Requirements

* No external dependencies

## Platform Support

* Unix/Linux
* macOS

## Configuration

The daemon extension is configurable with the following settings under a `[daemon]` section in the application configuration:

| Setting       | **Description**                                                              |
| ------------- | ---------------------------------------------------------------------------- |
| **user**      | The user name the process runs as.  Default: `os.getlogin()`                 |
| **group**     | The group name the process runs as. Default: *the primary group of the user* |
| **dir**       | The directory that the process runs in.  Default: `/`                        |
| **pid\_file** | The filesystem path to store the PID (Process ID) file.  Default: `None`     |
| **umask**     | The UMASK value to pass to `os.umask()`.  Default: `0`                       |

Configurations can be passed as defaults to `App`:

```python
from cement import App, init_defaults

DEFAULTS = init_defaults('myapp', 'daemon')
DEFAULTS['daemon']['user'] = 'myuser'
DEFAULTS['daemon']['group'] = 'mygroup'
DEFAULTS['daemon']['dir'] = '/var/lib/myapp/'
DEFAULTS['daemon']['pid_file'] = '/var/run/myapp/myapp.pid'
DEFAULTS['daemon']['umask'] = 0

class MyApp(App):
    class Meta:
        label = 'myapp'
        config_defaults = DEFAULTS
```

Application defaults are then overridden by configurations parsed via a `[demon]` config section in any of the applications configuration paths. An example configuration block would look like:

```
[daemon]
user = myuser
group = mygroup
dir = /var/lib/myapp/
pid_file = /var/run/myapp/myapp.pid
umask = 0
```

## Usage

The following example shows how to add the daemon extension, as well as trigger daemon functionality before `app.run()` is called.

```python
from time import sleep
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['daemon']

with MyApp() as app:
    app.daemonize()
    app.run()

    count = 0
    while True:
        count = count + 1
        print('Iteration: %s' % count)
        sleep(10)
```

Some applications may prefer to only daemonize certain sub-commands rather than the entire parent application. For example:

```python
from cement import App, Controller, ex

class Base(Controller):
    class Meta:
        label = 'base'

    @ex(help="run the daemon command.")
    def run_forever(self):
        from time import sleep
        self.app.daemonize()

        count = 0
        while True:
            count = count + 1
            print(count)
            sleep(10)

class MyApp(App):
    class Meta:
        label = 'myapp'
        handlers = [Base]
        extensions = ['daemon']

with MyApp() as app:
    app.run()
```

{% hint style="warning" %}
By default, even after `app.daemonize()` is called… the application will continue to run in the foreground, but will still manage the pid and user/group switching. To detach a process and send it to the background you simply pass the `--daemon` option at command line.
{% endhint %}

```
$ python example.py --daemon

$ ps -x | grep example
37421 ??         0:00.01 python example2.py --daemon
37452 ttys000    0:00.00 grep example
```

### Daemonizing Without Commandline Option

Some use cases might require daemonizing the process without having to always pass the `--daemon` option, or where passing the option might be redundant. You can work around that programatically by simply overriding the `daemon` argument value in order to force daemonization even if `--daemon` wasn’t passed.

```python
app.pargs.daemon = True
app.daemonize()
```

Note that this would only work **after** arguments have been parsed (i.e. after `app.run()` is called).


# Dummy

## Introduction

The Dummy Extension provides several placeholder type handlers to either mock operations or provide local-only usage during development. A perfect example is the [`DummyMailHandler`](http://cement.readthedocs.io/en/3.0/api/ext/ext_dummy/#cement.ext.ext_dummy.DummyMailHandler) that can be use during development or staging to prevent real email messages from being sent externally.

**API References:**

* [Cement Dummy Extension](http://cement.readthedocs.io/en/3.0/api/ext/ext_dummy/)

## Requirements

* No external dependencies

## Configuration

**DummyMailHandler**

This extension supports the following configuration settings under a `[mail.dummy]` configuration section:

| **Setting**         | **Description**                                                                                       |
| ------------------- | ----------------------------------------------------------------------------------------------------- |
| **to**              | Default recipient address (list, or comma separated depending on the config handler in use).          |
| **from\_addr**      | Default sender address                                                                                |
| **cc**              | Default carbon-copy addresses (list, or comma separated depending on the config handler in use)       |
| **bcc**             | Default blind-carbon-copy addresses (list, or comma separated depending on the config handler in use) |
| **subject**         | Default subject line                                                                                  |
| **subject\_prefix** | Additional string to prepend to the subject line of all messages                                      |

## Usage

{% tabs %}
{% tab title="Example: Using Dummy Extension" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['dummy']
        output_handler = 'dummy'
        template_handler = 'dummy'
        mail_handler = 'dummy'

with MyApp() as app:
    app.run()
```

{% endtab %}
{% endtabs %}


# Generate

## Introduction

The Generate Extension includes the [Generate](https://cement.readthedocs.io/en/3.0/api/ext/ext_generate/#cement.ext.ext_generate.Generate) controller, and provides a mechanism for generating common content from template directories. An example use case would be the ability for application developers to easily generate new plugins for their application… similar in other applications such as Chef Software’s `chef generate cookbook` type utilities.

The [Cement Developer Tools](/getting-started/developer-tools) use this extension to generate projects, plugins, extensions, scripts, etc for developers building their applications on the framework.

**Documentation References:**

* [Templating](/core-foundation/templating)

**API References:**

* [Cement Generate Extension](http://cement.readthedocs.io/en/3.0/api/ext/ext_generate/)

## **Requirements**

* pyYaml
* A valid [template handler](/core-foundation/templating) must be defined at the application level via [`App.Meta.template_handler`](http://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.template_handler) such as `jinja2`, `mustache`, etc.

{% hint style="info" %}
Cement 3.0.8+:

`pip install cement[generate]`
{% endhint %}

{% hint style="warning" %}
Applications using Cement <3.0.8 should continue to include `pyYaml` in their dependencies.
{% endhint %}

## **Configuration**

### **Application Configuration Settings**

This extension honors the following settings under the primary namespace (ex: `[myapp]`) of the application configuration:

| **Setting**       | **Description**                               |
| ----------------- | --------------------------------------------- |
| **template\_dir** | Directory path of a local template directory. |

### **Application Meta Options**

This extension honors the following [`App.Meta`](http://cement.readthedocs.io/en/3.0/api/core/foundation/?highlight=app.meta#cement.core.foundation.App.Meta) options:

| **Option**            | **Description**                                         |
| --------------------- | ------------------------------------------------------- |
| **template\_handler** | A template handler to use as the backend for templating |
| **template\_dirs**    | A list of data directories to look for templates        |
| **template\_module**  | A python module to look for templates                   |

## **Usage**

### **Examples**

{% tabs %}
{% tab title="Example: Using Generate Extension" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['generate', 'jinja2']
        template_handler = 'jinja2'


with MyApp() as app:
    app.run()
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py --help
usage: myapp [-h] [--debug] [--quiet] {generate} ...

optional arguments:
  -h, --help  show this help message and exit
  --debug     toggle debug output
  --quiet     suppress all output

sub-commands:
  {generate}
    generate  generate controller


$ python myapp.py generate --help
usage: myapp generate [-h] {plugin} ...

optional arguments:
  -h, --help  show this help message and exit

sub-commands:
  {plugin}
    plugin      generate plugin from template
```

{% endtab %}
{% endtabs %}

### **Generate Templates**

The Generate Extension looks for a `generate` sub-directory in all defined template directory paths defined at the application level. If it finds a `generate` directory it treats all items within that directory as a generate template.

A Generate Template requires a single configuration YAML file called `.generate.yml` that looks something like:

```yaml
---
ignore:
    - "^(.*)ignore-this(.*)$"
    - "^(.*)ignore-that(.*)$"

exclude:
    - "^(.*)exclude-this(.*)$"
    - "^(.*)exclude-that(.*)$"

variables:
    - name: 'my_variable_name'
      prompt: 'The Prompt Displayed to The User'
```

**Generate Template Configuration**

The following configurations are supported in a generate template’s config:

| **ignore**    | A list of regular expressions to match files that you want to completely ignore                    |
| ------------- | -------------------------------------------------------------------------------------------------- |
| **exclude**   | A list of regular expressions to match files that you want to copy only (not rendered as template) |
| **variables** | A list of variable definitions that support the following sub-keys:                                |

**Variable Definition Sub-Keys**

| **Key**      | **Description**                                                                                                                             |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| **name**     | The variable name exposed to the template context (required)                                                                                |
| **prompt**   | The prompt displayed to the user. Use `prompt: false` for a silent variable that takes its `default` without prompting (requires `default`) |
| **default**  | Default value (used on empty input, and as the value for `--defaults` runs)                                                                 |
| **case**     | Optional case transform applied to the value: one of `lower`, `upper`, `title`                                                              |
| **validate** | Optional regular expression the value must match (generation aborts on mismatch)                                                            |
| **type**     | Cement 3.0.16+ — one of `string` (default), `boolean`, `choice`. See [Typed Variables](#typed-variables) below                              |
| **extend**   | Cement 3.0.16+ — list of conditional-effect rules keyed on the resolved value. See [`extend:`](#extend-conditional-effects)                 |
| **requires** | Cement 3.0.16+ — gate this variable on other top-level variables. See [`requires:`](#requires-variable-gating)                              |

## Typed Variables

{% hint style="info" %}
Cement 3.0.16+
{% endhint %}

Typed variables let a generate template offer **optional features** — Y/N toggles and multi-choice pickers that conditionally prompt for extra variables, skip files, and gate on one another. Everything lives in the single `variables:` list of `.generate.yml`; each entry may carry a `type:` and optional `extend:` / `requires:` keys.

The mental model:

* A **`boolean`** or **`choice`** variable resolves to a real typed value at the **top level** of the template context — so `{% if docker %}`

  and `{% if web_framework == "flask" %}` work directly.
* An **`extend:`** rule fires when the resolved value matches its `when:`, contributing extra `variables:` (prompted in place), `ignore:` patterns (files skipped), and `exclude:` patterns (files copied verbatim).
* A **`requires:`** key gates a variable on other variables — if the gate fails, the variable is silently resolved to its `default` and none of its `extend:` rules fire.

### `type: string`

The classic variable — a plain `{name, prompt, default}` entry with optional `case:` / `validate:`. Omitting `type:` is equivalent to `type: string`, so existing templates are unaffected.

### `type: boolean`

A single y/N prompt rendered as `<prompt> [(Y)es/(N)o] [<default>]:`. With no `prompt:` key the label defaults to `Enable <name>`. Input `y`/`yes` maps to `True`, `n`/`no` to `False`, empty input to `default`. The resolved value is a real Python `bool`:

```yaml
variables:
    -   name: docker
        type: boolean
        default: true
        extend:
            -   when: true
                variables:
                    -   name: python_version
                        prompt: "Python Version (for Docker)"
                        default: "3.13"
            -   when: false
                ignore:
                    - '.*Dockerfile.*'
                    - '.*\.dockerignore.*'
```

For full control of the wording and accepted tokens, give `prompt:` an object — `accept:` / `reject:` are case-insensitive token lists that map the answer to a `bool` (input matching neither aborts, like a failed `validate:`):

```yaml
    -   name: docker
        type: boolean
        default: true
        prompt:
            text: "Use Docker? [(Y)ay/(N)ay]"
            accept: [y, yay]
            reject: [n, nay]
```

{% hint style="warning" %}
Quote bool-like tokens (`"yes"`, `"no"`, `"on"`, `"off"`) inside `accept:` / `reject:` — under YAML 1.1 they otherwise decode to a Python `bool` and the loader rejects them with a clear `ValueError`.
{% endhint %}

### `type: choice`

A numbered picker. Each option is either a bare scalar or an object with `value:` (required — the string the variable resolves to) and an optional `prompt:` label for the numbered list:

```yaml
    -   name: web_framework
        type: choice
        prompt: "Web Framework"
        default: "none"
        options:
            -   value: "none"
                prompt: "None — no web framework"
            -   value: "flask"
                prompt: "Flask Web Framework"
            -   value: "fastapi"
                prompt: "FastAPI Web Framework"
```

`default:` is **required** and must equal one of the option values (validated at config load). It is used on empty input and for `--defaults` runs.

### `extend:` — conditional effects

Each variable may carry an `extend:` list. A rule fires when its `when:` matches the resolved value:

| **Match form**     | **Example**                    | **Applies to**          |
| ------------------ | ------------------------------ | ----------------------- |
| Scalar equality    | `when: true` / `when: "flask"` | all types               |
| In-list membership | `when: ["flask", "fastapi"]`   | all types               |
| Regular expression | `when: "^3\\."`                | `string` variables only |

A firing rule contributes:

| **Key**       | **Effect**                                                                                                      |
| ------------- | --------------------------------------------------------------------------------------------------------------- |
| **variables** | Extra variables prompted *in place*, in declaration order (use `prompt: false` for silent values like versions) |
| **ignore**    | Regex patterns for files to skip entirely                                                                       |
| **exclude**   | Regex patterns for files to copy verbatim (not rendered as templates)                                           |

Multiple matching rules compose. An explicit YAML `null` block (e.g. `ignore:` with no items) coalesces to an empty list — it does not error.

### `requires:` — variable gating

A variable may be gated on other **top-level** variables:

```yaml
    -   name: docker_compose
        type: boolean
        default: true
        requires:
            - docker
```

Three forms are supported:

| **Form** | **Example**                                   | **Meaning**                   |
| -------- | --------------------------------------------- | ----------------------------- |
| List     | `requires: [docker]`                          | each named variable is truthy |
| Map      | `requires: {web_framework: flask}`            | equality                      |
| Map+list | `requires: {web_framework: [flask, fastapi]}` | in-list membership            |

Multiple entries are AND-ed and resolve order-independently — prerequisites are resolved (and prompted) before their dependents, regardless of declaration order. Interactive prompting is lazy: **declining a prerequisite skips the dependent's prompt entirely.**

{% hint style="warning" %}
**Gated-out is not forced-off.** When a `requires:` gate fails, the variable resolves to its (typed) **`default`** — it is not prompted, and none of its `extend:` rules fire. If the dependent's `default` is `true`, its files still render (only its `when: false` cleanup is skipped). If you want "declining the prerequisite drops the dependent's files too", put those `ignore:` patterns on the **prerequisite's** `when: false` rule.
{% endhint %}

A `requires:` gate can only reference other top-level variable names (nested `extend.variables` are not addressable), and a gated variable **must** have a `default:` — a missing default raises `ValueError`.

### CLI Invocation

```
# interactive: prompts for each variable, lazily (prerequisites first)
$ myapp generate webapp ./myproject

# headless: every variable takes its default, no prompts
$ myapp generate webapp ./myproject --defaults

# overwrite an existing destination
$ myapp generate webapp ./myproject --defaults --force

# copy the template source verbatim (no rendering, no prompts)
$ myapp generate webapp ./myproject --clone
```

### Using Values in Templates

Resolved values land at the **top level** of the template context — booleans as real `bool`s, choices as strings, and any `extend.variables` injected by a firing rule as ordinary top-level variables:

```django
{% if docker %}
COPY Dockerfile support files...
{% endif %}

{% if web_framework == "flask" %}
flask=={{ framework_version }}
{% endif %}
```

{% hint style="warning" %}
A boolean rendered as *text* (`{{ docker }}`) interpolates the capitalized Python repr — `True` / `False` — not `true`/`false`. This applies to both the jinja2 and mustache handlers. Use conditionals (`{% if docker %}`, mustache `{{#docker}}` / `{{^docker}}`) to gate content; only direct text interpolation shows the repr.
{% endhint %}

### Worked Example

The Cement source tree ships a complete working example under [`demo/generate-features/`](https://github.com/datafolklabs/cement/tree/main/demo/generate-features) — a `webapp` template combining a string variable (`project_name`), two booleans (`docker`, and `docker_compose` which `requires: [docker]`), and a choice (`web_framework`: none/flask/fastapi) with per-branch silent version variables.

Generated with `--defaults` (docker on, compose on, no framework):

```
myproject/
├── .dockerignore
├── Dockerfile
├── README.md
├── app.py
└── docker-compose.yml
```

Generated with `web_framework=fastapi` (everything else default):

```
myproject/
├── .dockerignore
├── Dockerfile
├── README.md
├── app.py
├── docker-compose.yml
├── requirements.txt    # fastapi==0.115 via the silent framework_version
└── wsgi.py
```

### Authoring Checklist

1. Start with your base `variables:` (plain strings) and template files.
2. Bucket the optional content — which files/variables belong to which toggle?
3. Add a `type: boolean` (or `choice`) variable per toggle.
4. Add `when: false` (or per-choice) `ignore:` rules for files to drop — remembering that a dependent's cleanup belongs on its **prerequisite's** decline branch if it must cascade.
5. Add `extend.variables` for follow-up prompts (or silent `prompt: false` metadata) on the enabling branch.
6. Add `requires:` for dependencies between toggles.
7. Gate rendered content inside files with `{% if <name> %}`.
8. Test **both** paths: `--defaults` and an interactive run that declines each toggle.

### Pitfalls & Validation

* **`exclude` vs `ignore`** — `exclude` still copies the file (verbatim, no rendering); `ignore` drops it entirely.
* **Anchor your regexes loosely** — patterns match against full paths, so use `'.*Dockerfile.*'`, not `'Dockerfile'`.
* **Cyclic `requires`** (A requires B, B requires A) fails fast with a clear `ValueError` — it will not hang or recurse.
* **`requires` references variable names only** — top-level `variables:` entries, not arbitrary template variables or nested `extend.variables`.
* Schema violations raise `ValueError` at config load (they survive `python -O`, unlike assertions): a `choice` with empty/missing `options`, a `default` not present in `options`, option objects without `value:`, bool-decoded tokens in `accept:`/`reject:`, a `requires:`-gated variable without a `default`, and `requires:` naming an unknown variable.


# Jinja2

## Introduction

The Jinja2 Extension provides the [`Jinja2OutputHandler`](http://cement.readthedocs.io/en/3.0/api/ext/ext_jinja2/#cement.ext.ext_jinja2.Jinja2OutputHandler) for output rendering, and the [`Jinja2TemplateHandler`](http://cement.readthedocs.io/en/3.0/api/ext/ext_jinja2/#cement.ext.ext_jinja2.Jinja2TemplateHandler) for file/content templating based on the Jinja2 templating language.

**Documentation References:**

* [Output Rendering](/core-foundation/output-rendering)
* [Templating](/core-foundation/templating)

**API References:**

* [Cement Jinja2 Extension](http://cement.readthedocs.io/en/3.0/api/ext/ext_jinja2/)
* [Jinja2 Module](http://jinja.pocoo.org/docs/2.10/api/)

## Requirements

* Jinja2

{% hint style="info" %}
Cement 3.0.8+:

`pip install cement[jinja2]`
{% endhint %}

{% hint style="warning" %}
Applications using Cement <3.0.8 should continue to include `jinja2` in their dependencies.
{% endhint %}

## Configuration

### **Application Configuration Settings**

This extension honors the following settings under the primary namespace (ex: `[myapp]`) of the application configuration:

| **Setting**       | **Description**                               |
| ----------------- | --------------------------------------------- |
| **template\_dir** | Directory path of a local template directory. |

### **Application Meta Options**

This extension honors the following [`App.Meta`](http://cement.readthedocs.io/en/3.0/api/core/foundation/?highlight=app.meta#cement.core.foundation.App.Meta) options:

| **Option**            | **Description**                                         |
| --------------------- | ------------------------------------------------------- |
| **template\_handler** | A template handler to use as the backend for templating |
| **template\_dirs**    | A list of data directories to look for templates        |
| **template\_module**  | A python module to look for templates                   |

## Usage

### **Output Handler**

{% tabs %}
{% tab title="Example: Using Jinja2 Output Handler" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['jinja2']
        output_handler = 'jinja2'

with MyApp() as app:
    app.run()

    # create some data
    data = {
        'foo': 'bar',
    }

    # render the data to STDOUT (default) via a template
    app.render(data, 'my_template.jinja2')
```

{% endtab %}
{% endtabs %}

### **Template Handler**

{% tabs %}
{% tab title="Example: Using Jinja2 Template Handler" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['jinja2']
        template_handler = 'jinja2'

with MyApp() as app:
    app.run()

    # create some data
    data = {
        'foo': 'bar'
    }

    # copy a source template directory to destination
    app.template.copy('/path/to/source/', 
                      '/path/to/destination/', 
                      data)

    # render any content as a template
    app.template.render('foo -> {{ foo }}', data)
```

{% endtab %}
{% endtabs %}


# Json

## Introduction

The JSON Extension provides the [`JsonOutputHandler`](http://cement.readthedocs.io/en/3.0/api/ext/ext_json/#cement.ext.ext_json.JsonOutputHandler) for output rendering in pure JSON, as well as the [`JsonConfigHandler`](http://cement.readthedocs.io/en/3.0/api/ext/ext_json/#cement.ext.ext_json.JsonConfigHandler) that allows applications to use JSON configuration files as a drop-in replacement of the default [`ConfigParserConfigHandler`](http://cement.readthedocs.io/en/3.0/api/ext/ext_configparser/#cement.ext.ext_configparser.ConfigParserConfigHandler).

**Documentation References:**

* [Configuration Settings](/core-foundation/configuration-settings)
* [Output Rendering](/core-foundation/output-rendering)

**API References:**

* [Cement Json Extension](http://cement.readthedocs.io/en/3.0/api/ext/ext_json/)
* [Python Json Library](https://docs.python.org/3/library/json.html)

## Requirements

* No external dependencies

## Configuration

This extension does not rely on any application level configuration settings or meta options.

### Using an Alternative Json Module

In some edge cases users have wanted to use an alternative json module for performance reasons, in particular [UltraJson](https://github.com/esnme/ultrajson). It is possible to override the backend `json` library module to use, such as `ujson` or another **drop-in replacement** library. The recommended solution would be to override the [`JsonOutputHandler.Meta.json_module`](http://cement.readthedocs.io/en/3.0/api/ext/ext_json/#cement.ext.ext_json.JsonConfigHandler.Meta.json_module):

{% tabs %}
{% tab title="Example: Using an Alternative Json Module" %}

```python
from cement import App, init_defaults

META = init_defaults('output.json', 'config.json')
META['output.json']['json_module'] = 'ujson'
META['config.json']['json_module'] = 'ujson'

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['json']
        meta_defaults = META
```

{% endtab %}
{% endtabs %}

## Usage

### Config Handler

{% tabs %}
{% tab title="Example: Using Json Config Handler" %}
{% code title="myapp.py" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['json']
        config_handler = 'json'
        config_file_suffix = '.json'
```

{% endcode %}

{% code title="\~/.myapp.json" %}

```
{
    "myapp": {
        "foo": "bar"
    }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

### Output Handler

In general, you likely would not set `output_handler` to `json`, but rather another type of output handler that displays readable output to the end-user (ex: Mustache, Jinja2, or Tabulate). However, Cement supports overriding handlers via command line options if the [`Handler.Meta.overridable`](http://cement.readthedocs.io/en/3.0/api/core/handler/#cement.core.handler.Handler.Meta.overridable) option is set. For example, `-o json` will trigger the framework to use the `json` output handler, overriding the default set in [`App.Meta.output_handler`](http://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.output_handler).

See the documentation on [Overriding Handlers via Command Line](/core-foundation/interfaces-and-handlers#overriding-handlers-via-command-line).

{% tabs %}
{% tab title="Example: Using Json Output Handler" %}
{% code title="myapp.py" %}

```python
from cement import App, init_defaults

META = init_defaults('output.json')
META['output.json']['overridable'] = True

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['json', 'mustache']
        meta_defaults = META
        output_handler = 'mustache'
        template_dir = './templates'

with MyApp() as app:
    app.run()

    data = {'foo': 'bar'}
    app.render(data, 'example.m')
```

{% endcode %}

{% code title="templates/example.m" %}

```
Foo: {{ foo }}
```

{% endcode %}
{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
Foo: bar

$ python myapp.py -o json
{"foo": "bar"}
```

{% endtab %}
{% endtabs %}


# Logging

## Introduction

The Logging Extension includes the LoggingLogHandler, and provides log handling based on the standard [`logging`](https://docs.python.org/3.6/library/logging.html#logging.Logger) library.

**Documentation References:**

* [Logging](/core-foundation/logging-1)

**API References:**

* [Cement Logging Extension](https://cement.readthedocs.io/en/3.0/api/ext/ext_logging/)
* [Python Logging Library](https://docs.python.org/3/library/logging.html)

## Requirements

* No external dependencies

## Configuration

### Application Configuration Settings

This handler honors the following settings under a `[log.logging]` section of the configuration:

| **Setting**     | **Description**                                                                                         |
| --------------- | ------------------------------------------------------------------------------------------------------- |
| **level**       | The logging to display logs for. One of `INFO, WARNING, ERROR, FATAL, DEBUG`. Default: `INFO`           |
| **file**        | The filesystem path of the log file.  Default: `None`                                                   |
| **to\_console** | Whether or not to log to console.  Default: `True`                                                      |
| **rotate**      | Whether or not rotate the log file.  Default: `False`                                                   |
| **max\_bytes**  | Maximum file size (in bytes) until the log file is rotated (if rotation is enabled).  Default: *512000* |
| **max\_files**  | Maximum number of files to keep when rotating is enabled.  Default: `4`                                 |

A sample config section might look like:

{% code title="\~/.myapp.conf" %}

```
[log.colorlog]
file = /path/to/config/file
level = info
to_console = true
rotate = true
max_bytes = 512000
max_files = 4
```

{% endcode %}

### **Toggle Log Level via Command-line**

This extension supports an optional feature to add a command-line argument to toggle the log level. This feature is not enabled by default for one specific reason: the log level will not be modified until **after** argument parsing happens. This can lead to a lot of confusion for developers who might not see their debug logs from a `pre_setup` hook, or anything that happens before argument parsing completes. For this reason, you should use this feature with caution and thus we disable it by default.

You can enable the log level argument by setting via [`App.Meta.meta_defaults`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.meta_defaults) for the `log.logging` handler:

{% tabs %}
{% tab title="Example: Enabling Log Level Argument" %}

```python
from cement import App, init_defaults

META = init_defaults('log.logging')
META['log.logging']['log_level_argument'] = ['-l', '--level']

class MyApp(App):
    class Meta:
        label = 'myapp'
        meta_defaults = META
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py --help
usage: myapp [-h] [--debug] [--quiet] [-l {info,warning,error,debug,fatal}]

optional arguments:
  -h, --help            show this help message and exit
  --debug               full application debug mode
  --quiet               suppress all output
  -l {info,warning,error,debug,fatal}
                        logging level


$ python myapp.py
INFO: This is an info message
WARNING: This is an warning message
ERROR: This is an error message
CRITICAL: This is a fatal message

$ python myapp.py -l error
ERROR: This is an error message
CRITICAL: This is a fatal message
```

{% endtab %}
{% endtabs %}

## Usage

See the [Logging Documentation](/core-foundation/logging-1).


# Memcached

## Introduction

The Memcached Extension includes the [`MemcachedCacheHandler`](https://cement.readthedocs.io/en/3.0/api/ext/ext_memcached/#cement.ext.ext_memcached.MemcachedCacheHandler) and provides application caching and key/value store support via Memcached.

**Documentation References:**

* [Caching](/core-foundation/caching)

**API References:**

* [Cement Memcached Extension](https://cement.readthedocs.io/en/3.0/api/ext/ext_memcached/)
* [Pylibmc Library](http://sendapatch.se/projects/pylibmc/)

## Requirements

* Pylibmc
  * There are known issues installing `pylibmc` on macOS/Homebrew via PIP.  [This post might be helpful](http://stackoverflow.com/questions/14803310/error-when-install-pylibmc-using-pip).

{% hint style="info" %}
Cement 3.0.8+:

`pip install cement[memcached]`
{% endhint %}

{% hint style="warning" %}
Applications using Cement <3.0.8 should continue to include `pylibmc` in their dependencies.
{% endhint %}

## Configuration

This extension honors the following config settings under a `[cache.memcached]` section in any configuration file:

| **Setting**      | **Description**                                                                                           |
| ---------------- | --------------------------------------------------------------------------------------------------------- |
| **expire\_time** | The default time in seconds to expire items in the cache.  Default: `0` (does not expire)                 |
| **hosts**        | List of memcached servers (comma separated if using a plain text based config handler like configparser). |

## Usage

{% tabs %}
{% tab title="Example: Using Memcached Cache Handler" %}
{% code title="myapp.py" %}

```python
from cement import App
from cement.utils.misc import init_defaults

CONFIG = init_defaults('myapp', 'cache.memcached')
CONFIG['cache.memcached']['expire_time'] = 300 # seconds
CONFIG['cache.memcached']['hosts'] = ['127.0.0.1']

class MyApp(App):
    class Meta:
        label = 'myapp'
        config_defaults = CONFIG
        extensions = ['memcached']
        cache_handler = 'memcached'

with MyApp() as app:
    # Run the app
    app.run()

    # Set a cached value
    app.cache.set('my_key', 'my value')

    # Get a cached value
    app.cache.get('my_key')

    # Delete a cached value
    app.cache.delete('my_key')

    # Delete the entire cache
    app.cache.purge()
```

{% endcode %}

{% code title="\~/.myapp.conf" %}

```
[myapp]

# set the cache handler to use
cache_handler = memcached


[cache.memcached]

# time in seconds that an item in the cache will expire
expire_time = 3600

# comma seperated list of memcached servers
hosts = 127.0.0.1, cache.example.com
```

{% endcode %}
{% endtab %}
{% endtabs %}


# Mustache

## Introduction

The Mustache Extension provides output and file templating based on the [Mustache Templating Language](http://mustache.github.com/).

**Documentation References:**

* [Output Rendering](/core-foundation/output-rendering)
* [Templating](/core-foundation/templating)

**API References**

* [Cement Mustache Extension](https://cement.readthedocs.io/en/3.0/api/ext/ext_mustache/)
* [Mustache Library](http://mustache.github.io/)

## Requirements

* Pystache

{% hint style="info" %}
Cement 3.0.8+:

`pip install cement[mustache]`
{% endhint %}

{% hint style="warning" %}
Applications using Cement <3.0.8 should continue to include `pystache` in their dependencies.
{% endhint %}

## Configuration

### **Application Configuration Settings**

This extension honors the following settings under the primary namespace (ex: `[myapp]`) of the application configuration:

| **Setting**       | **Description**                               |
| ----------------- | --------------------------------------------- |
| **template\_dir** | Directory path of a local template directory. |

### **Application Meta Options**

This extension honors the following [`App.Meta`](http://cement.readthedocs.io/en/3.0/api/core/foundation/?highlight=app.meta#cement.core.foundation.App.Meta) options:

| **Option**            | **Description**                                         |
| --------------------- | ------------------------------------------------------- |
| **template\_handler** | A template handler to use as the backend for templating |
| **template\_dirs**    | A list of data directories to look for templates        |
| **template\_module**  | A python module to look for templates                   |

## Usage

### Output Handler

{% tabs %}
{% tab title="Example: Mustache Output Handler" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['mustache']
        output_handler = 'mustache'

with MyApp() as app:
    app.run()

    # create some data
    data = {
        'foo': 'bar',
    }

    # render the data to STDOUT (default) via a template
    app.render(data, 'my_template.mustache')
```

{% endtab %}
{% endtabs %}

### **Template Handler**

{% tabs %}
{% tab title="Example: Using Mustache Template Handler" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['mustache']
        template_handler = 'mustache'

with MyApp() as app:
    app.run()

    # create some data
    data = {
        'foo': 'bar'
    }

    # copy a source template directory to destination
    app.template.copy('/path/to/source/', 
                      '/path/to/destination/', 
                      data)

    # render any content as a template
    app.template.render('foo -> {{ foo }}', data)
```

{% endtab %}
{% endtabs %}

### Loading Partials

Mustache supports `partials`, or in other words template `includes`. These are also loaded by the output handler, but require a full file name. The partials will be loaded in the same way as the base templates.

{% tabs %}
{% tab title="Example: Using Mustache Partials" %}
{% code title="templates/base.mustache" %}

```python
Inside base.mustache
{{> partial.mustache}}
```

{% endcode %}

{% code title="templates/partial.mustache" %}

```
Inside partial.mustache
```

{% endcode %}
{% endtab %}
{% endtabs %}

The above would output:

```
Inside base.mustache
Inside partial.mustache
```


# Plugin

## Introduction

The Plugin Extension handles application plugin support, and is the default plugin handler used by Cement.

**Documentation References:**

* [Application Plugins](/core-foundation/plugins)

**API References:**

* [Cement Plugin Extension](https://cement.readthedocs.io/en/3.0/api/ext/ext_plugin/)

## Requirements

* no external dependencies

## Usage

For usage information see [Application Plugins](/core-foundation/plugins).


# Print

## Introduction

The Print Extension adds the [`PrintOutputHandler`](http://cement.readthedocs.io/en/3.0/api/ext/ext_print/#cement.ext.ext_print.PrintOutputHandler) and [`PrintDictOutputHandler`](http://cement.readthedocs.io/en/3.0/api/ext/ext_print/#cement.ext.ext_print.PrintDictOutputHandler) to render output in pure text. It is mostly intended for development, but also supports the additional `app.print()`extended function which can be used in place of the standard `print()` so that apps can continue to utilize features of the framework consistently (such as honoring [`pre_render`](/core-foundation/hooks#pre_render) and [`post_render`](/core-foundation/hooks#post_render)hooks, etc).

**Documentation References:**

* [Output Rendering](/core-foundation/output-rendering)

**API References:**

* [Cement Print Extension](https://cement.readthedocs.io/en/3.0/api/ext/ext_print/)

## Requirements

* No external dependencies

## Configuration

This extension does not support any application level configuration settings or meta options.

## Usage

{% tabs %}
{% tab title="Example: Using Print Output Handler" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['print']

with MyApp() as app:
    app.run()
    app.print('This is an output message')
```

{% endtab %}
{% endtabs %}

Alternatively, you can use the `print_dict` output handler that can be useful in development as it simply just prints out a string representation of the data dict.

{% tabs %}
{% tab title="Example: Using Print Dict Output Handler" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['print_dict']
        output_handler = 'print_dict'

with MyApp() as app:
    app.run()

    data = {
        'foo' : 'bar',
    }

    app.render(data)
```

{% endtab %}
{% endtabs %}


# Redis

## Introduction

The Redis Extension provides application caching and key/value store support via Redis.

Documentation References:

* [Caching](/core-foundation/caching)

API References:

* [Cement Redis Extension](https://cement.readthedocs.io/en/3.0/api/ext/ext_redis/)
* [Redis Library](https://redislabs.com/lp/python-redis/)

## Requirements

* Redis

{% hint style="info" %}
Cement 3.0.8+:

`pip install redis`
{% endhint %}

{% hint style="warning" %}
Applications using Cement <3.0.8 should continue to include `redis` in their dependencies.
{% endhint %}

## Configuration

This extension honors the following config settings under a `[cache.redis]` section in any configuration file:

| **Setting**      | **Description**                                                                           |
| ---------------- | ----------------------------------------------------------------------------------------- |
| **expire\_time** | The default time in seconds to expire items in the cache.  Default: `0` (does not expire) |
| **host**         | Redis server ip address or hostname                                                       |
| **port**         | Redis server port                                                                         |
| **db**           | Redis server database id/namespace                                                        |

## Usage

{% tabs %}
{% tab title="Example: Using Redis Cache Handler" %}
{% code title="myapp.py" %}

```python
from cement import App, init_defaults

CONFIG = init_defaults('myapp', 'cache.redis')
CONFIG['cache.redis']['expire_time'] = 300 # seconds
CONFIG['cache.redis']['host'] = '127.0.0.1'
CONFIG['cache.redis']['port'] = 6379
CONFIG['cache.redis']['db'] = 0

class MyApp(App):
    class Meta:
        label = 'myapp'
        config_defaults = CONFIG
        extensions = ['redis']
        cache_handler = 'redis'

with MyApp() as app:
    # Run the app
    app.run()

    # Set a cached value
    app.cache.set('my_key', 'my value')

    # Get a cached value
    app.cache.get('my_key')

    # Delete a cached value
    app.cache.delete('my_key')

    # Delete the entire cache
    app.cache.purge()
```

{% endcode %}

{% code title="\~/.myapp.conf" %}

```
[myapp]

# set the cache handler to use
cache_handler = redis


[cache.redis]

# time in seconds that an item in the cache will expire
expire_time = 300

# Redis server
host = 127.0.0.1

# Redis port
port = 6379

# Redis database number
db = 0
```

{% endcode %}
{% endtab %}
{% endtabs %}


# Scrub

## Introduction

The Scrub Extension provides an easy mechanism for obfuscating sensitive information from command line output. It is useful for debugging and for providing end-user output to developers without including sensitive info like IP addresses, phone numbers, credit card numbers, etc.

Scrubbing happens in a [`post_render`](/core-foundation/hooks#pre_render) hook by iterating over the list of tuples in `App.Meta.scrub`and calling `re.sub()` on the text provided by the output handler in use. Therefore, all output produced by `app.render()` will be scrubbed… including JSON, YAML, or any other output handler.

**API References:**

* [Cement Scrub Extension](https://cement.readthedocs.io/en/3.0/api/ext/ext_scrub/)

## **Requirements**

* No external dependencies

## **Configuration**

### Application Configuration Settings

This extension does not rely on any application level configuration settings or meta options.

### **Application Meta Data**

This extension honors the following `App.Meta` options:

| Option    | **Description**                                                  |
| --------- | ---------------------------------------------------------------- |
| **scrub** | A list of tuples in the form of `[ ( 'REGEX', 'REPLACEMENT' ) ]` |

## **Usage**

{% tabs %}
{% tab title="Example: Using Scrub Extension" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['scrub', 'print']
        scrub = [
            # obfuscate ipv4 addresses
            (r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", '***.***.***.***'),
        ]

with MyApp() as app:
    app.run()
    app.print('This is an IPv4 Address: 192.168.1.100')
```

{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
This is an IPv4 Address: 192.168.1.100

$ python myapp.py --scrub
This is an IPv4 Address: ***.***.***.***
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
In order for scrubbing to work, output must be rendered via a registered [output handler](/core-foundation/output-rendering). If only printing to console is desired, use the `print` extension along with `app.print()` (as in the above example).
{% endhint %}


# SMTP

## Introduction

The SMTP Extension includes the [`SMTPMailHandler`](https://cement.readthedocs.io/en/3.0/api/ext/ext_smtp/#cement.ext.ext_smtp.SMTPMailHandler), and provides the ability for applications to send email via standard SMTP.

**Documentation References:**

* [Mail Messaging](/core-foundation/mail-messaging)

**API References:**

* [Cement SMTP Extension](https://cement.readthedocs.io/en/3.0/api/ext/ext_smtp)
* [Python SMTP Library](https://docs.python.org/3/library/smtplib.html)

## Requirements

* No external depencies

## Configuration

### Application Configuration Settings

This extension supports the following configuration settings under a `[mail.smtp]` configuration section:

| **Setting**         | **Description**                                                                                       |
| ------------------- | ----------------------------------------------------------------------------------------------------- |
| **to**              | Default recipient address (list, or comma separated depending on the config handler in use).          |
| **from\_addr**      | Default sender address                                                                                |
| **cc**              | Default carbon-copy addresses (list, or comma separated depending on the config handler in use)       |
| **bcc**             | Default blind-carbon-copy addresses (list, or comma separated depending on the config handler in use) |
| **subject**         | Default subject line                                                                                  |
| **subject\_prefix** | Additional string to prepend to the subject line of all messages                                      |
| **host**            | The SMTP host server address. Default: `localhost`                                                    |
| **port**            | The SMTP host server port. Default: `25`                                                              |
| **timeout**         | The timeout in seconds before terminating a connection. Default: 30                                   |
| **ssl**             | Whether to initiate SSL or not. Default: `False`                                                      |
| **tls**             | Whether to use TLS or not (requires SSL). Default: `False`                                            |
| **auth**            | Whether or not to initiate SMTP authentication. Default: `False`                                      |
| **username**        | SMTP authentication username. Default: `None`                                                         |
| **password**        | SMTP authentication password. Default: `None`                                                         |

## Usage

{% tabs %}
{% tab title="Example: Using SMTP Mail Handler" %}
{% code title="myapp.py" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        mail_handler = 'smtp'

with MyApp() as app:
    app.run()
    
    # send a message
    app.mail.send('This is my fake message',
        subject='This is my subject',
        to=['john@example.com', 'rita@example.com'],
        from_addr='me@example.com',
    )
    
    # send text/html message
    app.mail.send(("message", "<body>message</body>"),
        subject='This is my subject',
        to=['john@example.com'],
        from_addr='me@example.com',
    )
    
    # send file attachments
    app.mail.send("message", 
        subject='This is my subject',
        to=['john@example.com'],
        from_addr='me@example.com',
        files=['/path/to/file.ext']
    )
```

{% endcode %}

{% code title="\~/.myapp.conf" %}

```
[myapp]

# set the mail handler to use
mail_handler = smtp


[mail.smtp]

# default to addresses (comma separated list)
to = me@example.com

# default from address
from = someone_else@example.com

# default cc addresses (comma separated list)
cc = jane@example.com, rita@example.com

# default bcc addresses (comma separated list)
bcc = blackhole@example.com, someone_else@example.com

# default subject
subject = This is The Default Subject

# additional prefix to prepend to the subject
subject_prefix = MY PREFIX >

# smtp host server
host = localhost

# smtp host port
port = 465

# timeout in seconds
timeout = 30

# whether or not to establish an ssl connection
ssl = true

# whether or not to use start tls
tls = true

# whether or not to initiate smtp auth
auth = true

# smtp auth username
username = john.doe

# smtp auth password
password = oober_secure_password
```

{% endcode %}
{% endtab %}
{% endtabs %}


# Tabulate

## Introduction

The Tabulate Extension includes the [`TabulateOutputHandler`](https://cement.readthedocs.io/en/3.0/api/ext/ext_tabulate/#cement.ext.ext_tabulate.TabulateOutputHandler), and provides output handling based on the [Tabulate](https://pypi.python.org/pypi/tabulate) library. Its format is familiar to users of MySQL, Postgres, etc.

**Documentation References:**

* [Output Rendering](/core-foundation/output-rendering)

**API References:**

* [Cement Tabulate Extension](https://cement.readthedocs.io/en/3.0/api/ext/ext_tabulate)
* [Tabulate Library](https://github.com/gregbanks/python-tabulate)

## Requirements

* Tabulate

{% hint style="info" %}
Cement 3.0.8+:

`pip install cement[tabulate]`
{% endhint %}

{% hint style="warning" %}
Applications using Cement <3.0.8 should continue to include `tabulate` in their dependencies.
{% endhint %}

## Configuration

This extension does not support any application level configuration settings or meta options.

## Usage

{% tabs %}
{% tab title="Example: Using Tabulate Output Handler" %}
{% code title="myapp.py" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['tabulate']
        output_handler = 'tabulate'

with MyApp() as app:
    app.run()

    # create a dataset
    headers = ['NAME', 'AGE', 'ADDRESS']
    data = [
        ["Krystin Bartoletti", 47, "PSC 7591, Box 425, APO AP 68379"],
        ["Cris Hegan", 54, "322 Reubin Islands, Leylabury, NC 34388"],
        ["George Champlin", 25, "Unit 6559, Box 124, DPO AA 25518"],
        ]

    app.render(data, headers=headers)
```

{% endcode %}
{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
| NAME               | AGE | ADDRESS                                 |
|--------------------+-----+-----------------------------------------|
| Krystin Bartoletti |  47 | PSC 7591, Box 425, APO AP 68379         |
| Cris Hegan         |  54 | 322 Reubin Islands, Leylabury, NC 34388 |
| George Champlin    |  25 | Unit 6559, Box 124, DPO AA 25518        |
```

{% endtab %}
{% endtabs %}


# Yaml

## Introduction

The Yaml Extension includes the [`YamlOutputHandler`](http://cement.readthedocs.io/en/3.0/api/ext/ext_yaml/#cement.ext.ext_yaml.YamlOutputHandler) to render output in pure Yaml, as well as the [`YamlConfigHandler`](http://cement.readthedocs.io/en/3.0/api/ext/ext_yaml/#cement.ext.ext_yaml.YamlConfigHandler) that allows applications to use Yaml configuration files as a drop-in replacement of the default [`ConfigParserConfigHandler`](https://cement.readthedocs.io/en/3.0/api/ext/ext_configparser/#cement.ext.ext_configparser.ConfigParserConfigHandler).

**Documentation References:**

* [Configuration Settings](/core-foundation/configuration-settings)
* [Output Rendering](/core-foundation/output-rendering)

**API References:**

* [Cement Yaml Extension](https://cement.readthedocs.io/en/3.0/api/ext/ext_yaml/)
* [Yaml Library](https://pyyaml.org/wiki/PyYAMLDocumentation)

## Requirements

* pyYaml

{% hint style="info" %}
Cement 3.0.8+:

`pip install cement[yaml]`
{% endhint %}

{% hint style="warning" %}
Applications using Cement <3.0.8 should continue to include `pyYaml` in their dependencies.
{% endhint %}

## Configuration

This extension does not support any application level configuration settings or meta options.

## Usage

### Config Handler

{% tabs %}
{% tab title="Example: Using Yaml Config Handler" %}
{% code title="myapp.py" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['yaml']
        config_handler = 'yaml'
        config_file_suffix = '.yml'
```

{% endcode %}

{% code title="\~/.myapp.yml" %}

```
---
myapp:
    foo: bar
```

{% endcode %}
{% endtab %}
{% endtabs %}

### Output Handler

In general, you likely would not set `output_handler` to `yaml`, but rather another type of output handler that displays readable output to the end-user (ex: Mustache, Jinja2, or Tabulate). However, Cement supports overriding handlers via command line options if the [`Handler.Meta.overridable`](http://cement.readthedocs.io/en/3.0/api/core/handler/#cement.core.handler.Handler.Meta.overridable) option is set. For example, `-o yaml` will trigger the framework to use the `yaml` output handler, overriding the default set in [`App.Meta.output_handler`](http://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.output_handler).

See the documentation on [Overriding Handlers via Command Line](/core-foundation/interfaces-and-handlers#overriding-handlers-via-command-line).

{% tabs %}
{% tab title="Example: Using Yaml Output Handler" %}
{% code title="myapp.py" %}

```python
from cement import App, init_defaults

META = init_defaults('output.yaml')
META['output.yaml']['overridable'] = True

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['yaml', 'mustache']
        meta_defaults = META
        output_handler = 'mustache'
        template_dir = './templates'

with MyApp() as app:
    app.run()
    data = {'foo': 'bar'}
    app.render(data, 'example.m')
```

{% endcode %}

{% code title="templates/example.m" %}

```
Foo: {{ foo }}
```

{% endcode %}
{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
Foo: bar

$ python myapp.py -o yaml
{foo: bar}
```

{% endtab %}
{% endtabs %}


# Watchdog

## Introduction

The Watchdog Extension includes the [`WatchdogManager`](https://cement.readthedocs.io/en/3.0/api/ext/ext_watchdog/#cement.ext.ext_watchdog.WatchdogManager), enabling applications to easily monitor, and react to, changes in filesystem paths based on the filesystem events monitoring library [Watchdog](https://pypi.python.org/pypi/watchdog).

On application startup, the Watchdog Observer is automatically started and then upon application close, the observer thread is properly stopped and joined with the parent process before exit.

**API References:**

* [Cement Watchdog Extension](https://cement.readthedocs.io/en/3.0/api/ext/ext_watchdog/)
* [Watchdog Library](https://pythonhosted.org/watchdog/)

## Requirements

* Watchdog

{% hint style="info" %}
Cement 3.0.8+:

`pip install cement[watchdog]`
{% endhint %}

{% hint style="warning" %}
Applications using Cement <3.0.8 should continue to include `watchdog` in their dependencies.
{% endhint %}

## Platform Support

* Unix/Linux
* macOS
* Windows

## Configuration

### Application Configuration Settings

This extension does not support any application level configuration settings.

### Application Meta Options

This extension honors the following application meta options:

| Option              | **Description**                                                                                                                                                                                                                             |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **watchdog\_paths** | A list of tuples that are passed directly as arguments to [`WatchdogManager.add()`](https://cement.readthedocs.io/en/3.0/api/ext/ext_watchdog/#cement.ext.ext_watchdog.WatchdogManager.add) (a shortcut equivalent to `app.watchdog.add()`. |

## Hooks

This extension defines the following hooks:

### watchdog\_pre\_start

Run first when `App.watchdog.start()` is called. The application object is passed as an argument. Nothing is expected in return.

### watchdog\_post\_start

Run last when `App.watchdog.start()` is called. The application object is passed as an argument. Nothing is expected in return.

### watchdog\_pre\_stop

Run first when `App.watchdog.stop()` is called. The application object is passed as an argument. Nothing is expected in return.

### watchdog\_post\_stop

Run last when `App.watchdog.stop()` is called. The application object is passed as an argument. Nothing is expected in return.

### watchdog\_pre\_join

Run first when `App.watchdog.join()` is called. The application object is passed as an argument. Nothing is expected in return.

### watchdog\_post\_join

Run last when `App.watchdog.join()` is called. The application object is passed as an argument. Nothing is expected in return.

## Usage

The following example uses the default `WatchdogEventHandler` that by default only logs all events to `debug`:

{% tabs %}
{% tab title="Example: Using Watchdog Extension" %}

```python
from time import sleep
from cement import App, CaughtSignal
from cement.ext.ext_watchdog import WatchdogEventHandler

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['watchdog']
        watchdog_paths = [
            ('./tmp/', WatchdogEventHandler),
        ]

with MyApp() as app:
    app.run()
    try:
        while True:
            sleep(1)
    except CaughtSignal as e:
        print(e)
```

{% endtab %}
{% endtabs %}

In the above example, nothing is printed to console. However you will see something like the following via debug logging:

```
$ python myapp.py --debug 2>&1 | grep -i watchdog
cement.core.extension : loading the 'cement.ext.ext_watchdog' framework extension
cement.core.hook : defining hook 'watchdog_pre_start'
cement.core.hook : defining hook 'watchdog_post_start'
cement.core.hook : defining hook 'watchdog_pre_stop'
cement.core.hook : defining hook 'watchdog_post_stop'
cement.core.hook : defining hook 'watchdog_pre_join'
cement.core.hook : defining hook 'watchdog_post_join'
cement.core.hook : registering hook 'watchdog_extend_app' from cement.ext.ext_watchdog into hooks['post_setup']
cement.core.hook : registering hook 'watchdog_add_paths' from cement.ext.ext_watchdog into hooks['post_setup']
cement.core.hook : registering hook 'watchdog_start' from cement.ext.ext_watchdog into hooks['pre_run']
cement.core.hook : registering hook 'watchdog_cleanup' from cement.ext.ext_watchdog into hooks['pre_close']
cement.core.hook : running hook 'post_setup' (<function watchdog_extend_app at 0x103c991e0>) from cement.ext.ext_watchdog
cement.core.foundation : extending appication with '.watchdog' (<cement.ext.ext_watchdog.WatchdogManager object at 0x103f83ef0>)
cement.core.hook : running hook 'post_setup' (<function watchdog_add_paths at 0x103ddd6a8>) from cement.ext.ext_watchdog
cement.ext.ext_watchdog : adding path /path/to/tmp with event handler <class 'cement.ext.ext_watchdog.WatchdogEventHandler'>
cement.core.hook : running hook 'pre_run' (<function watchdog_start at 0x103ddd598>) from cement.ext.ext_watchdog
cement.ext.ext_watchdog : starting watchdog observer
myapp : Watchdog Event: <FileDeletedEvent: src_path='/path/to/tmp/test2'>
myapp : Watchdog Event: <FileDeletedEvent: src_path='/path/to/tmp/test4'>
myapp : Watchdog Event: <FileDeletedEvent: src_path='/path/to/tmp/test3'>
myapp : Watchdog Event: <FileDeletedEvent: src_path='/path/to/tmp/dir1/test'>
myapp : Watchdog Event: <FileDeletedEvent: src_path='/path/to/tmp/test'>
myapp : Watchdog Event: <DirDeletedEvent: src_path='/path/to/tmp/dir1'>
myapp : Watchdog Event: <DirModifiedEvent: src_path='/path/to/tmp'>
myapp : Watchdog Event: <DirModifiedEvent: src_path='/path/to/tmp'>
myapp : Watchdog Event: <DirCreatedEvent: src_path='/path/to/tmp/dir1'>
myapp : Watchdog Event: <FileCreatedEvent: src_path='/path/to/tmp/dir1/test.file'>
myapp : Watchdog Event: <DirModifiedEvent: src_path='/path/to/tmp/dir1'>
cement.core.hook : running hook 'pre_close' (<function watchdog_cleanup at 0x10e930620>) from cement.ext.ext_watchdog
cement.ext.ext_watchdog : stopping watchdog observer
cement.ext.ext_watchdog : joining watchdog observer
cement.core.foundation : closing the myapp application
```

To expand on the above example, we can add our own event handlers:

{% tabs %}
{% tab title="Example: Adding Watchdog Event Handlers" %}
{% code title="myapp.py" %}

```python
from time import sleep
from cement import App, CaughtSignal
from cement.ext.ext_watchdog import WatchdogEventHandler

class MyEventHandler(WatchdogEventHandler):
    def on_any_event(self, event):
        # do something with the ``event`` object
        print("The modified path was: %s" % event.src_path)

class MyApp(App):
    class Meta:
        label = 'myapp'
        extensions = ['watchdog']
        watchdog_paths = [
            ('./tmp/', MyEventHandler),
        ]

with MyApp() as app:
    app.run()

    try:
        while True:
            sleep(1)
    except CaughtSignal as e:
        print(e)
```

{% endcode %}
{% endtab %}

{% tab title="cli" %}

```
$ python myapp.py
The modified path was: /path/to/tmp/test.file
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Note that the `WatchdogEventHandler` could be replaced with any other event handler classe (i.e. those available from `watchdog` directly). However to play nicely with Cement, we sub-class them first in order to pass in our application object.
{% endhint %}

{% tabs %}
{% tab title="Example: Creating a Watchdog Event Handler" %}

```python
from watchdog.events import FileSystemEventHandler

class MyEventHandler(FileSystemEventHandler):
    def __init__(self, app, *args, **kw):
        super(MyEventHandler, self).__init__(*args, **kw)
        self.app = app
```

{% endtab %}
{% endtabs %}

For full usage of Watchdog event handlers, refer to the [Watchdog API Documentation](http://pythonhosted.org/watchdog/index.html).


# Additional Topics


# Extending The App Object

The [`App.extend()`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.extend) method provides a mechanism that allows plugins, extensions, or the app itself to add objects or functions to the global application object.

For example, a plugin might extend the `App` with an `api` member allowing developers to call `app.api.get(...)`. The application itself does not provide `app.api`. However, the plugin does. As plugins are often third party, it is not possible for the plugin developer to simply sub-class the `App` class and add the functionality because the class is already instantiated by the time plugins are loaded.

{% tabs %}
{% tab title="Example: Extending the App Object" %}

```python
from cement import App

def example_func():
    print('Inside example_func')

def extend_myapp(app):
    app.extend('example', example_func)

class MyApp(App):
    class Meta:
        label = 'myapp'
        hooks = [
            ('post_setup', extend_myapp),
        ]

with MyApp() as app:
    app.run()

    # call the extended object or function
    app.example()
```

Alternatively from within an extension or plugin:

```python
def example_func():
    print('Inside example_func')

def extend_myapp(app):
    app.extend('example', example_func)

def load(app):
    app.hook.register('post_setup', extend_myapp)
```

{% endtab %}

{% tab title="cli" %}

```
$ python test.py
Inside example_func
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Extended members can be anything from instantiated objects to callables of any kind. Its use case is varied and arbitrary... but should be documented well by the developer that is extending it.
{% endhint %}


# Unit Testing

## Introduction

Unit testing Cement apps is as straight forward as any other Python library. Cement uses, and recommends the following utilities, but there are no limitations to what tools you choose to use:

* [Pytest](https://docs.pytest.org/en/7.1.x/): Unit testing.
* [Coverage](https://coverage.readthedocs.io/en/6.4.1/): Monitors code while unit tests run to ensure all code is tested.
* [Flake8](https://flake8.pycqa.org/en/latest/): Style-guide enforcement

Cement has a strict policy that all framework code has 100% test coverage, and 100% style-guide clearance before any releases are published. This is not required for applications built on Cement, but it is highly recommended for quality.

For examples, feel free to browse the [framework testing library](https://github.com/datafolklabs/cement/tree/main/tests) on Github.

## Special Considerations

### Sub-class TestApp

Cement apps sub-class from [`cement.core.foundation.App`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App), however for testing there are some things we want to override to make things more portable/reliable. For example, in testing we do not want to parse `~/.myapp.yml` (example local user configuration file), as this may skew tests from one developer machine to the next.

Cement includes an additional [`cement.core.foundation.TestApp`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.TestApp) that can also be sub-classed to easily override App.Meta for testing.

This looks something like:

```python
class TestApp(App):
    class Meta:
        label = "app-%s" % misc.rando()[:12]
        argv = []
        core_system_config_files = []
        core_user_config_files = []
        config_files = []
        core_system_config_dirs = []
        core_user_config_dirs = []
        config_dirs = []
        core_system_template_dirs = []
        core_user_template_dirs = []
        core_system_plugin_dirs = []
        core_user_plugin_dirs = []
        plugin_dirs = []
        exit_on_close = False
```

To use this class, it is best to create a separate `MyAppTest` class that sub-classes both from `TestApp` and your `MyApp`:

```python
class MyAppTest(TestApp,MyApp):
    """A sub-class of MyApp that is better suited for testing."""

    class Meta:
        label = 'myapp'
```

{% hint style="info" %}
Note the order of sub-classing is important so that `Meta` is overridden properly.
{% endhint %}

### CLI Arguments and Options

As most apps built on Cement are command-line based, passing arguments and options to `MyApp` is important. This is easily handled by passing the [`argv`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.argv) list:

```python
myargs = ['some-command', '--some-option', '--etc']
with MyAppTest(argv=myargs) as app:
    app.run()
```

The above is equivalent to running the following at the command line:

```
myapp some-command --some-option --etc
```

### Temp Files/Dirs

Working with files and directories is common for apps built on Cement, which can be easily done using the [`fs.Tmp()`](https://cement.readthedocs.io/en/3.0/api/utils/fs/#cement.utils.fs.Tmp) utility in combination with [Pytest fixtures](https://docs.pytest.org/en/6.2.x/fixture.html). These fixtures can be automatically loaded from `tests/conftest.py`:

*myapp/tests/conftest.py:*

```python
import pytest
from cement import fs

@pytest.fixture(scope="function")
def tmp(request):
    """
    Create a `tmp` object that generates a unique temporary directory, and file
    for each test function that requires it.
    """
    t = fs.Tmp()
    yield t
    t.remove()
```

This creates a `tmp` fixture that we can use anywhere in our tests, and most importantly when the test is complete the temp object (file and directory) are automatically removed.

myapp/tests/test\_myapp.py:

```python
def test_myapp(tmp):
    with MyAppTest() as app:
        # do something with tmp.file/tmp.dir
        app.run()
```

{% hint style="info" %}
Note the `tmp` fixture is passed to each test function, creating a unique instance of it for each test.
{% endhint %}

## Writing Tests

In Pytest, tests are loaded from files matching `test_`, and functions matching `test_`. Some developers prefer to keep tests alongside the file it is testing (for example: `main.py` and `test_main.py`). Cement developers prefer putting all tests in a separate `tests/` directory:

```
├── CHANGELOG.md
├── README.md
├── myapp
│   ├── __init__.py
│   ├── controllers
│   │   ├── __init__.py
│   │   └── base.py
│   ├── main.py
├── requirements.txt
├── setup.py
└── tests
    ├── conftest.py
    ├── controllers
    │   └── test_base.py
    └── test_main.py
```

A typical test is just a simple function that executes some logic, and asserts some conditions:

```python
def test_myapp_debug():
    # ensure debug is false by default
    with MyTestApp() as app:
        assert app.debug is False
        
    # ensure debug option toggles app.debug
    with MyTestApp(argv=['--debug']) as app:
        assert app.debug is True
```

In the above example, we tested two conditions (whether `--debug` was passed or not), and asserted those conditions. If either assertion failed, the test would fail.

## Running Tests

Running tests with Pytest can be done by running `pytest` in the root of your project directory. That said, to add support for coverage.py you likely want to create a helper script (Makefile, Fabric, etc) to execute all the things at once.

Cement `generate project` includes support for `coverage.py` out of the box, and also includes a `Makefile` with helpers:

*myapp/Makefile:*

```
test: 
    python -m pytest
        -v
        --cov=myapp
        --cov-report=term
        --cov-report=html:coverage-report
        tests/
```

And this is run by:

```
make test
```

{% hint style="info" %}
The above example generates an HTML coverage report in `./coverage-report/index.html`. Open that file in your local browser to review code that is not getting hit by tests, and write tests to touch that code for better coverage.

Note that `--cov=myapp` is telling coverate to only report on your code, rather than including all other libraries your code has imported/executed.
{% endhint %}


# Cleanup

## Introduction to Application Cleanup

The concept of cleanup after application run time is nothing new, but often ignored or forgotten by developers. What happens during cleanup all depends on the application. This might mean closing and deleting temporary files, removing session data, or deleting a PID (Process ID) file for example.

To allow for application cleanup not only within your program, but also external plugins and extensions, there is the [`app.close()`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.close) method that must be called after [`app.run()`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.run) regardless of any exceptions or runtime errors.

{% hint style="info" %}
When using the Python `with` operator, the `App.close()` method is automatically called when exiting the block.
{% endhint %}

Calling [`app.close()`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.close) ensures that the [`pre_close`](/core-foundation/hooks#cement-framework-hooks) and [`post_close`](/core-foundation/hooks#cement-framework-hooks) framework hooks are run, allowing extensions/plugins/etc to cleanup after the program runs.

## Exit Status and Error Codes

You can optionally configure your application to automatically call `sys.exit()` as well as set the status code that your application exists with via the meta option [App.Meta.exit\_on\_close](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.exit_on_close) as well as setting `App.exit_code`:

{% tabs %}
{% tab title="Example: Exit Status and Error Codes" %}

```python
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        exit_on_close = True

with MyApp() as app:
    try:
        app.run()
    except SomeException as e:
        # do something with e
        app.log.fatal('Caught Exception: %s' % e)
        app.exit_code = 100
```

{% endtab %}
{% endtabs %}

Note the use of the `App.exit_on_close` meta option. Cement **will not** call `sys.exit()` unless this is set to `True`. You will find that calling `sys.exit()` in testing is very problematic, therefore you will likely want to enable `exit_on_close` in production, but not for testing as in this example:

{% tabs %}
{% tab title="Example: Disable Exit on Close in Testing" %}

```python
# create a separate class for unit tests

class MyTestApp(MyApp):
    class Meta:
        exit_on_close = False
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
The default exit code is `0`. However, any uncaught exceptions will cause the application to exit with a code of `1` (error).
{% endhint %}

## Running Cleanup Code

Any extension, or plugin, or even the application itself that has cleanup code should do so within the `pre_close` or `post_close` framework hooks to ensure that it gets run.

{% tabs %}
{% tab title="Example: Running Cleanup Code" %}

```python
def my_cleanup_code(app):
    # do something to cleanup
    if os.path.exists('/path/to/some/dir'):
        os.remove('/path/to/some/dir')

def load(app):
    app.hook.register('pre_close', my_cleanup_code)
```

{% endtab %}
{% endtabs %}


# Signal Handling

## Introduction to Signal Handling

Python provides the [Signal](http://docs.python.org/library/signal.html) library allowing developers to catch Unix signals and set handlers for asynchronous events. For example, the `SIGTERM` (Terminate) signal is received when issuing a `kill` command for a given Unix process. Via the signal library, we can set a handler (function) callback that will be executed when that signal is received. Some signals however can not be handled/caught, such as the `SIGKILL` signal (i.e. `kill -9`). Please refer to the [Signal](http://docs.python.org/library/signal.html) library documentation for a full understanding of its use and capabilities.

A caveat when setting a signal handler is that only one handler can be defined for a given signal. Therefore, all handling must be done from a single callback function. This is a slight roadblock for applications built on Cement in that many pieces of the framework are broken out into independent extensions as well as applications that have 3rd party plugins. The trouble happens when the application, plugins, and framework extensions all need to perform some action when a signal is caught. This section outlines the recommended way of handling signals with Cement versus manually setting signal handlers that may collide.

{% hint style="warning" %}
It is important to note that it is not necessary to use the Cement mechanisms for signal handling, what-so-ever. That said, the primary concern of the framework is that `app.close()` is called no matter what the situation so that the `pre_close` and `post_close` framework hooks get run for cleanup.

Therefore, if you decide to disable signal handling all together you **must** ensure that you at the very least catch `signal.SIGTERM` and `signal.SIGINT` with the ability to call `app.close()` (or allow the `with` operator to exit properly).

You will likely find that it is more complex than you might think. The reason we put these mechanisms in place is primarily that we found it was the best way to a) handle a signal, and b) have access to our `app` object in order to be able to call `app.close()` when a process is terminated.
{% endhint %}

## Signals Caught by Default

By default Cement catches the signals `SIGTERM`, `SIGINT`, and `SIGHUP`. When these signals are caught, Cement raises the exception `CaughtSignal(signum, frame)` where `signum` and `frame` are the parameters passed to the signal handler. By raising an exception, we are able to pass runtime back to our applications main process (within a try/except block) and maintain the ability to access our application object without using global objects.

A basic application using default handling might look like:

{% tabs %}
{% tab title="Example: Default Signal Handling" %}

```python
import signal
from cement import App, CaughtSignal

with App('myapp') as app:
    try:
        app.run()
    except CaughtSignal as e:
        # do something with e.signum or e.frame
        if e.signum == signal.SIGTERM:
            app.log.warning('Caught SIGTERM')
        elif e.signum == signal.SIGINT:
            app.log.warning('Caught SIGINT')
```

{% endtab %}
{% endtabs %}

The above provides a very simple means of handling the most common signals, which in turn allows our application to "exit clean" by running `app.close()` and any `pre_close` or `post_close` hooks (via `__exit__` from the `with` operator).

{% hint style="warning" %}
If we don't catch the signals, then the exceptions will be unhandled and the application will not exit clean.
{% endhint %}

## Using the Signal Hook

An alternative way of adding multiple callbacks to a signal handler is by using the Cement `signal` hook. This hook is called anytime a handled signal is encountered.

{% tabs %}
{% tab title="Example: Using the Signal Hook" %}
{% code title="myapp.py" %}

```python
import signal
from cement import App, CaughtSignal

def my_signal_handler(app, signum, frame):
    # do something with app
    app.log.warning('Inside my_signal_handler')

    # do something with signum, or frame
    sig_name = signal.Signals(signum)
    print('Caught Signal %s' % sig_name)

class MyApp(App):
    class Meta:
        label = 'myapp'
        hooks = [
            ('signal', my_signal_handler),
        ]

with MyApp() as app:
    try:
        app.run()
    except CaughtSignal as e:
        # do something with e.signum, e.frame
        pass
```

{% endcode %}

Alternatively for extensions and plugins:

```python
def my_signal_handler(app, signum, frame):
    # do something with app
    app.log.warning('Inside my_signal_handler')

    # do something with signum, or frame
    sig_name = signal.Signals(signum)
    print('Caught Signal %s' % sig_name)

def load(app):
    app.hook.register('signal', my_signal_handler)
```

{% endtab %}
{% endtabs %}

The key thing to note here is that the main application itself can easily handle the `CaughtSignal` exception without using hooks. However, using the `signal` hook is useful for plugins and extensions to be able to tie into the signal handling outside of the main application. Both serve the same purpose.

Regardless of how signals are handled, all extensions or plugins should use the `pre_close` hook for cleanup purposes as much as possible as it is always run when `app.close()` is called.

## Configuring Which Signals To Catch

You can define what signals to catch via [App.Meta.catch\_signals](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.App.Meta.catch_signals).

{% tabs %}
{% tab title="Example: Configuring Which Signals to Catch" %}

```python
import signal
from cement import App

class MyApp(App):
    class Meta:
        label = 'myapp'
        catch_signals = [
            signal.SIGTERM,
            signal.SIGINT,
            signal.SIGHUP,
        ]
```

{% endtab %}
{% endtabs %}

What happens is, Cement iterates over the `App.Meta.catch_signals` list and adds a generic handler function (the same) for each signal. Because the handler calls the cement `signal` hook, and then raises an exception which both pass the `signum` and `frame` parameters, you are able to handle the logic elsewhere rather than assigning a unique callback function for every signal.

## What If I Don't Like Your Signal Handler Callback?

If you want more control over what happens when a signal is caught, you are more than welcome to override the default signal handler callback. That said, please be kind and be sure to at least run the cement `signal` hook within your callback.

The following is an example taken from the builtin [`cement_signal_handler`](https://cement.readthedocs.io/en/3.0/api/core/foundation/#cement.core.foundation.cement_signal_handler) callback. Note that there is a bit of hackery in how we are acquiring the `CementApp` from the frame. This is because the signal is picked up outside of our control so we need to find it.

{% tabs %}
{% tab title="Example: Overriding the Builtin Signal Handler Callback" %}

```python
from cement import App

def my_signal_handler(signum, frame):
    """
    Catch a signal, run the ``signal`` hook, and then raise an exception
    allowing the app to handle logic elsewhere.

    Args:
        signum (int): The signal number
        frame: The signal frame

    Raises:
        cement.core.exc.CaughtSignal: Raised, passing ``signum``, and ``frame``

    """
    LOG.debug('Caught signal %s' % signum)

    for f_global in frame.f_globals.values():
        if isinstance(f_global, App):
            app = f_global
            for res in app.hook.run('signal', app, signum, frame):
                pass  # pragma: nocover

    raise exc.CaughtSignal(signum, frame)

class MyApp(App):
    class Meta:
        label = 'myapp'
        signal_handler = my_signal_handler
```

{% endtab %}
{% endtabs %}

## This Is Stupid, and UnPythonic - How Do I Disable It?

To each their own. If you simply do not want any kind of signal handling performed, just set `App.Meta.catch_signals = None`.


# Pipenv

## Introduction to Pipenv

From the [Pipenv documentation](https://pipenv.pypa.io/en/latest/):

> **Pipenv** is a tool that aims to bring the best of all packaging worlds (bundler, composer, npm, cargo, yarn, etc.) to the Python world. *Windows is a first-class citizen, in our world.*
>
> It automatically creates and manages a virtualenv for your projects, as well as adds/removes packages from your `Pipfile` as you install/uninstall packages. It also generates the ever-important `Pipfile.lock`, which is used to produce deterministic builds.

{% hint style="info" %}
Cement maintainers do not currently use Pipenv, therefore this documentation is here as a helper. Future versions of Cement may include Pipenv configurations out-of-the-box (but do not currently).
{% endhint %}

## Installing Pipenv

Pipenv can be installed via Pip:

```
pip install pipenv
```

## Using Pipenv With Cement

First install Cement, and generate a project:

```bash
pip install cement

cement generate project ./myapp
```

In the generated `./myapp` directory:

```bash
### setup requirements

pipenv install -r requirements.txt


### setup requirements for dev

pipenv install -r requirements-dev.txt --dev
```

This will create the `Pipfile` and `./Pipfile.lock`. You will then need to modify `Pipfile` to include the application console script:

```
[scripts]
myapp = "python -m myapp.main"
```

Your app can then be run under `pipenv`:

```
pipenv run myapp --help
```

{% hint style="info" %}
You can then remove the `requirements.txt` and `requirements-dev.txt` if no longer needed.
{% endhint %}


# Autocomplete

## Introduction to Autocomplete

Autocomplete, or autosuggest, is a common feature for many command-line applications. Most command-line users are familiar with autocomplete when they type part of a command and press `tab` to complete the rest of the command, or `tab-tab` to see a list of commands matching that prefix.&#x20;

Beyond autocomplete of the command name itself, there are ways to autocomplete sub-commands and/or options and arguments. As support for autocomplete often depends on external applications, and/or the terminal application you are using, autocomplete is a varied topic.

Cement does not currently have any mechanisms to support autocomplete out of the box. This document will serve as a helper for known ways you might find suitable for your needs.

## Fig

[Fig](https://fig.io) is "The next-generation command line" (per their site), with a suit of products that includes [IDE-Style Autocomplete for 500+ CLI tools](https://fig.io/user-manual/autocomplete).

*video from their site*

{% embed url="<https://fig.io/videos/main-demo-grey.mp4>" %}

Fig has built a Cement Extension that can be installed via PyPi, and included in your applications that are Built on Cement™.

See:

* [Fig Autocomplete & Cement](https://fig.io/docs/guides/integrating/integrations/cement)

## ZSH Auto Suggestions

Provides "Fish-like fast/unobtrusive autosuggestions for zsh".

See:

* [github.com/zsh-users/zsh-autosuggestions](https://github.com/zsh-users/zsh-autosuggestions)

## BASH Programmable Completion

BASH has mechanisms for implementing "Programmable Completion".

See:

* [BASH Manual](https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html)
* [github.com/scop/bash-completion](https://github.com/scop/bash-completion)


# Profiling with cProfile

Cement apps can be profiled with cProfile very easily, however there are some considerations as it may not work "out of the box" as expected. This doc comes as the output of the following issue on Github:

* <https://github.com/datafolklabs/cement/issues/547>

{% hint style="info" %}
The following assumes that your Cement project was created from the developer tools; `cement generate project`. This is not necessary, however the use of `myapp.main` assumes the Cement App, and `main()` function live here. Modify to suit.

For your actual app, replace `myapp` with your Python package name for your app.
{% endhint %}

References:

* <https://docs.python.org/3/library/profile.html>
* <https://www.turing.com/kb/python-code-with-cprofile>

### Profiling Commands

In order to profile specific commands within our app, we need to save cProfile to an output file. For basic example, we can run `myapp --help` with cProfile with the following, which will save our profile to the file `prof.dat`:

```
python -m cProfile -o prof.dat -m myapp.main --help
```

The output file should probably named appropriately based on what you are profiling. For example, if I need to profile `command1` I will save that to it's own profile output file.

```
python -m cProfile -o prof-command1.dat -m myapp.main command1
Inside MyApp.command1()
```

### Inspecting a Profile

Now that we have our commands profiled, we can inspect that same as any other program. Here we are opening up the `prof.dat` with `pstats`:

```
python -m pstats prof.dat
Welcome to the profile statistics browser.
prof.dat%
```

You might want to sort by "cumulative time" (`cumtime`) and then review the stats:

```
prof.dat% sort cumtime

prof.dat% stats

Tue Jan  2 03:07:11 2024    prof.dat

         150506 function calls (146817 primitive calls) in 0.202 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    182/1    0.002    0.000    0.202    0.202 {built-in method builtins.exec}
        1    0.000    0.000    0.202    0.202 <string>:1(<module>)
        1    0.000    0.000    0.202    0.202 /usr/local/lib/python3.8/runpy.py:197(run_module)
        1    0.000    0.000    0.197    0.197 /usr/local/lib/python3.8/runpy.py:64(_run_code)
        1    0.000    0.000    0.197    0.197 /src/tmp/myapp/myapp/main.py:2(<module>)
   195/12    0.001    0.000    0.191    0.016 <frozen importlib._bootstrap>:986(_find_and_load)
   195/12    0.001    0.000    0.191    0.016 <frozen importlib._bootstrap>:956(_find_and_load_unlocked)
   186/14    0.001    0.000    0.185    0.013 <frozen importlib._bootstrap>:650(_load_unlocked)
   158/14    0.001    0.000    0.184    0.013 <frozen importlib._bootstrap_external>:837(exec_module)
   248/14    0.000    0.000    0.177    0.013 <frozen importlib._bootstrap>:211(_call_with_frames_removed)
    44/25    0.000    0.000    0.155    0.006 {built-in method builtins.__import__}
        1    0.000    0.000    0.107    0.107 /src/tmp/myapp/myapp/main.py:57(main)
        1    0.000    0.000    0.103    0.103 /src/cement/core/foundation.py:1733(__enter__)
        1    0.000    0.000    0.103    0.103 /src/cement/core/foundation.py:880(setup)
        1    0.000    0.000    0.100    0.100 /src/cement/core/foundation.py:1269(_setup_extension_handler)
        2    0.000    0.000    0.100    0.050 /src/cement/core/extension.py:135(load_extensions)
        9    0.000    0.000    0.100    0.011 /src/cement/core/extension.py:99(load_extension)
        1    0.000    0.000    0.069    0.069 /src/cement/__init__.py:4(<module>)
    76/55    0.000    0.000    0.065    0.001 <frozen importlib._bootstrap>:1017(_handle_fromlist)
        1    0.000    0.000    0.053    0.053 /src/cement/core/foundation.py:1(<module>)
      159    0.002    0.000    0.050    0.000 <frozen importlib._bootstrap_external>:909(get_code)
        1    0.000    0.000    0.040    0.040 /src/cement/ext/ext_jinja2.py:1(<module>)
        1    0.000    0.000    0.039    0.039 /usr/local/lib/python3.8/site-packages/jinja2/__init__.py:1(<module>)
      260    0.001    0.000    0.038    0.000 /usr/local/lib/python3.8/re.py:289(_compile)
  685/647    0.007    0.000    0.038    0.000 {built-in method builtins.__build_class__}
      103    0.000    0.000    0.037    0.000 /usr/local/lib/python3.8/re.py:250(compile)
        1    0.000    0.000    0.037    0.037 /usr/local/lib/python3.8/site-packages/jinja2/environment.py:1(<module>)
       83    0.000    0.000    0.037    0.000 /usr/local/lib/python3.8/sre_compile.py:759(compile)
      159    0.007    0.000    0.032    0.000 <frozen importlib._bootstrap_external>:1029(get_data)
      192    0.001    0.000    0.027    0.000 <frozen importlib._bootstrap>:890(_find_spec)
      188    0.000    0.000    0.024    0.000 <frozen importlib._bootstrap_external>:1399(find_spec)
      188    0.002    0.000    0.024    0.000 <frozen importlib._bootstrap_external>:1367(_get_spec)
        1    0.000    0.000    0.023    0.023 /src/cement/ext/ext_smtp.py:1(<module>)
        1    0.000    0.000    0.022    0.022 /src/cement/core/arg.py:1(<module>)
      321    0.003    0.000    0.021    0.000 <frozen importlib._bootstrap_external>:1498(find_spec)
      [SNIPPED]
```


# Debugging with VSCode

{% hint style="warning" %}
The following documentation has been adding by [community submission](https://github.com/datafolklabs/cement/issues/738), and has not yet been fully verified/tested.  Replace `<myapp>` with the Python module name of your application.
{% endhint %}

The following are notes on how to setup debugging in VSCode for applications Built on Cement. It has been tested on Cement 3.x on Windows 11.

### Implementation Steps

* Run > Open Configurations
* Run > Add Configurations
  * Select Python Debugger > Module > `<myapp>.main` &#x20;

Modify the configuration code block to allow for arguments/options:

*launch.json*

```json
"configurations": [
  {
    "name": "Python Debugger: Cement CLI Tool",
    "type": "debugpy",
    "request": "launch",
    "module": "<myapp>.main"
    "console": "integratedTerminal",
    "args": "${command:pickArgs}"
  }
]
```

The above configuration will prompt for arguments/options when Debug runs. An alternative approach might be to hard-code the arguments/options if you are frequently debugging a specific action and do not want to add it every time.

```json
"args": [ "list", "-h" ]
```


# Environment Variables

## Cement Environment Variables

### CEMENT\_LOG

Parsed by the core framework, and extensions early on in runtime (before `App` is fully loaded). Triggers low-level framework logging, and toggles `App.Meta.framework_logging`.

Values:&#x20;

* `0`
* `1`

Usage:

```
export CEMENT_LOG=1
```

{% hint style="info" %}
This variable was introduced in Cement v3.0.8, and deprecates the previous setting [`CEMENT_FRAMEWORK_LOGGING`](https://docs.builtoncement.com/pages/BKKRWDUkncx4bT2liT3U#3.0.8-1).
{% endhint %}

### CEMENT\_FRAMEWORK\_LOGGING

Deprecated in 3.0.8 in favor of [CEMENT\_LOG](#cement_log) (same usage).

## Overriding App Configuration

Out of the box, Cement supports overriding application configuration settings by environment variables.

Configuration:

```yaml
myapp:
  foo: bar
```

The above configuration would be overridden by the `$MYAPP_FOO` environment variable.

```
export MYAPP_FOO=not-bar
```


# Terminology

## Controller Stacking

In Cement, there are two ways that [application controllers](/core-foundation/controllers) can be implemented:

* **embedded**: The controller's sub-commands, arguments, and options are embedded within its parent controller's namespace.  To the end-user, usage would appear to be part of the parent controller. Examples:
  * `myapp embedded-sub-command`
  * `myapp --embedded-option`
  * etc
* **nested**: The controller's sub-comands, arguments, and options are nested below its parent controller's namespace.  To the end-user, usage would require prefixing sub-commands with the controller's namespace.  Examples:
  * `myapp nested-controller nested-sub-command`
  * `myapp nested-controller --nested-option`

## Minimal, Complete, Verifiable Example (MCVE)

Cement has adopted this term from a post on [Stack Overflow](https://stackoverflow.com/help/mcve). "MCVE" is used to refer to something as a "complete working example". Generally this is used most often on Github when interacting with users, often times reporting bugs or other issues, where a working example is required to reproduce said issue.

## Runtime

Runtime encompasses the entire execution from the moment the application is called at the command line, all the way through to exit. In Cement, this generally involves the following primary steps:

* App Setup
* App Run
* App Close

## Runtime Dispatch

A sub-step within the application runtime that we use to refer to the process of parsing the command-line, processing arguments, mapping sub-commands to controllers, and executing the specified controller function.


# Contributing

## Introduction

Cement is an open-source project, and is open to any and all contributions that other developers would like to provide. This document provides some guidelines that all contributors should be aware of, and abide by to have their submissions included in the source.

## Licensing

The Cement source code is licensed under the BSD three-clause license and is approved by the [Open Source Initiative](http://www.opensource.org/). All contributed source code must be either the original work of the contributing author, which will be contributed under the BSD license, or work taken from another project that is released under a BSD-compatible license.

## Submitting Bug Reports and Feature Requests

If you've found a bug, or would like to request a feature please create a detailed issue for it at [github.com/datafolklabs/cement](http://github.com/datafolklabs/cement/issues).

**The ideal bug report would include:**

* Bug description
* The version of Python, Cement, and any dependencies in use
* Steps to reproduce the bug
* Code samples that show the bug in action
* A pull request including code that:

  a. Fixes the bug

  b. Atleast one test case that tests for the bug specifically

**The ideal feature request would include:**

* Feature description
* Example code, or pseudo code of how you might use the feature
* Example command line session showing how the feature would be used by the end-user
* A pull request including:

  a. The feature you would like added

  b. At least one test case that tests the feature and maintains 100% code coverage when tests are run (meaning that your tests should cover 100% of your contributed code)

  c. Documentation that outlines how to use the feature

## Guidelines for Code Contributions

If you are new to Cement, looking for something quick to fix, or just want an opportunity to contribute to the project, the best place to start is to review the issues labeled as `low-hanging-fruit` on [Github](https://github.com/datafolklabs/cement/labels/low-hanging-fruit).

All contributors should attempt to abide by the following:

* Contributors fork the project on GitHub onto their own account
* All changes should be commited, and pushed to their repository
* All pull requests are from a topic branch, not an existing Cement branch
* Contributors make every effort to comply with [PEP8](http://www.python.org/dev/peps/pep-0008/)​
* Before starting on a new feature, or bug fix, always do the following:
  * `git pull --rebase` to get latest changes from upstream
  * Checkout a new branch. For example:
    * `git checkout -b feature/<feature_name>`
    * `git checkout -b bug/<bug_number>`
* Code must include the following:
  * All tests pass successfully
  * Coverage reports 100% code coverage when running tests
  * New features are documented in the appropriate section of the doc
  * Significant changes are mentioned in the ChangeLog
* All contributions must be associated with at least one issue in GitHub. If the issue does not exist, create one (per the guidelines above).
* Commit comments must include something like the following:
  * `Resolves Issue #1127`
  * `Partially Resolves Issue #9873`
* A single commit per issue.
* Contributors should add their full name or handle to the CONTRIBUTORS file.

Regarding git commit messages, please read the following:

* ​[Commit Guidelines](http://git-scm.com/book/en/Distributed-Git-Contributing-to-a-Project#Commit-Guidelines)​

## Source Code and Versioning

One of the primary goals of Cement is stability in the source code. For this reason we maintain a number of different git branches for focused development.

**Development Branches**

Active 'forward' development happens out of two branches:

* `master` - Development for the next minor stable release.
* `portland` - Development for the next major release.

Additionally, specific development branches might exist in the future for larger releases that may require iterative 'release candidate' handling before an official stable release. These branches will have the format of:

* `dev/3.1.x`
* `dev/3.3.x`
* `dev/4.1.x`
* `dev/4.3.x`
* `etc`

**Stable Branches**

* `stable/0.8.x`
* `stable/1.0.x`
* `stable/1.2.x`
* `stable/2.0.x`
* `stable/2.2.x`
* `stable/3.0.x`
* `stable/3.2.x`
* `etc`

There is a system for versioning that may seem complex, and needs some explanation. Version numbers are broken up into three parts:

* `<Major>.<Minor>.<Bugfix>`

This means:

* **Major** - The major version of the source code generally relates to extensive incompatible changes, or entire code base rewrites. Applications built on the `1.x.x` version of Cement will need to be completely rewritten for the `2.x.x` versions of Cement.
* **Minor** - The minor version signifies the addition of new features. It may also indicate minor incompatibilities with the previous stable version, but should be easily resolvable with minimal coding effort.
* **Bugfix** - During the lifecycle of a stable release such as `2.2.x`, the only updates should be bug and/or security related. At times, minor features may be introduced during a 'bugfix' release but that should not happen often.

It should be noted that both the Minor, and Bugfix versions follow a `even == stable`, and `odd == development` scheme. Therefore, the current version in git will always end in an 'odd number'. For example, if the current stable version is `2.0.18`, then the version in `stable/2.0.x` would be `2.0.19`. That said, the `master` branch might then be `2.1.1` which is the first version of the next minor release. Bugfixes would get applied to both branches, however feature updates would only be applied to `master`. The next stable release would then be `2.2.0` and a new git branch of `stable/2.2.x` will be created.

The `portland` branch is always very forward looking, and will contain significant (and likely broken) code changes. It should never be used for anything other than development and testing.

## New Release Checklist

For maintainers before finalizing a release, create a Github issue called `Cement X.YY.Z Release Tracker` with the following:

```
- [ ] 100% Test Passing on Travis CI
    - [ ] Python 3.7
    - [ ] Python 3.8
    - [ ] Python 3.9
    - [ ] Python 3.10
    - [ ] Python 3.11
- [ ] 100% Test Coverage
- [ ] Core Tests on Windows
- [ ] Cement CLI Smoke Tests
    - [ ] Linux
    - [ ] macOS
    - [ ] Windows
- [ ] Git Builds 
    - Archs:
        - linux/amd64
        - linux/arm64
    - Tags:
        - [ ] X
        - [ ] X.Y
        - [ ] X.Y.Z
- [ ] Git Merge to Version Branch
    - stable/X.Y
- [ ] API Documentation Builds (Read The Docs)
    - [ ] X.Y
- [ ] Developer Documentation (Gitbook)
    - [ ] stable/X.Y
    - [ ] Update Change Log
    - [ ] Update Release Notes
    - [ ] Update Deprecations
- [ ] Docker Image Builds (Docker Hub)
    - [ ] datafolklabs/cement:X
    - [ ] datafolklabs/cement:X.Y
    - [ ] datafolklabs/cement:X.Y.Z
- [ ] PyPi Distribution
- [ ] Notify mailing list
- [ ] Notify Slack channel
```

*Replace X.Y.Z with the release versions.*

## Misc

### Multi-arch Docker Images

```
docker buildx build \
    --platform linux/amd64,linux/arm64 \
    --push \
    -t datafolklabs/cement:latest \
    .
```


# Privacy Policy

## Google Analytics

Placeholder for official policy some day.

This documentation uses standard Google Analytics to track and measure usage. Collected data includes browser/device type, general location, etc. We do not collect or sell personal information.


# Cement 2.10 Documentation

{% hint style="info" %}
The Developer Guide, and API Reference for versions before Cement 3.0 are both hosted on Read The Docs.

* [Cement 2.10 Documentation](https://cement.readthedocs.io/en/2.10)
  {% endhint %}

###


