### Setup Development Environment Source: https://github.com/datafolklabs/cement/blob/main/cement/cli/templates/generate/project/README.md Install dependencies and set up the virtual environment for development using the Makefile. ```bash make setup ``` -------------------------------- ### Setup macOS Development Environment Source: https://github.com/datafolklabs/cement/blob/main/README.md Installs pipx and pdm, creates a virtual environment, installs dependencies (excluding memcached), and runs core tests. This sequence sets up a native development environment on macOS. ```bash pip install pipx pipx install pdm pdm venv create pdm install --without memcached make test-core ``` -------------------------------- ### Install Cement Framework Source: https://github.com/datafolklabs/cement/blob/main/README.md Install the core Cement framework using pip. This is the basic installation for most use cases. ```bash pip install cement ``` -------------------------------- ### Install Cement Project Source: https://github.com/datafolklabs/cement/blob/main/cement/cli/templates/generate/project/README.md Install the Cement project using pip. ```bash pip install . ``` -------------------------------- ### App.setup Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/foundation.md Initializes the application by performing all setup actions. This method is called before `run()`, allowing for pre-execution configuration. ```APIDOC ## App.setup ### Description Initializes the application by performing all setup actions. This method is called before `run()`, allowing for pre-execution configuration. All handlers should be instantiated and callable after setup is complete. ``` -------------------------------- ### Install Cement from PyPI Source: https://github.com/datafolklabs/cement/blob/main/cement/cli/templates/generate/project/README.md Install the Cement project from a built distribution or PyPI release using pip. ```bash pip install {{ label }} ``` -------------------------------- ### Create Development Virtual Environment on Windows Source: https://github.com/datafolklabs/cement/blob/main/README.md Creates a development virtual environment using pdm and installs project dependencies, excluding memcached. This is part of the native Windows development setup. ```bash pdm venv create pdm install --without memcached ``` -------------------------------- ### Install pipx and pdm on Windows Source: https://github.com/datafolklabs/cement/blob/main/README.md Installs pipx and then uses pipx to install pdm, a package manager. This is a prerequisite for setting up the development environment on Windows. ```bash pip install pipx pipx install pdm ``` -------------------------------- ### Setup Handler Class Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/handler.md Sets up a handler class, making it ready for use. This is typically called after resolving a handler that needs initialization or setup procedures. ```python for controller in app.handler.list('controller'): ch = app.handler.setup(controller) ``` -------------------------------- ### Start Services with Devbox Source: https://github.com/datafolklabs/cement/blob/main/README.md In one terminal, use this command to start the required services like Redis, Memcached, and Mailpit via Process Compose. ```bash make up ``` -------------------------------- ### Initialize Devbox Environment Source: https://github.com/datafolklabs/cement/blob/main/README.md Run this command to initialize the Devbox environment and install all necessary dependencies for development. ```bash make init ``` -------------------------------- ### Setup Development Environment Source: https://github.com/datafolklabs/cement/blob/main/cement/cli/templates/generate/todo-tutorial/README.md Creates a virtual environment for development and activates it. Also shows how to run the todo CLI application and tests. ```bash make virtualenv source env/bin/activate todo --help make test ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/datafolklabs/cement/blob/main/cement/cli/templates/generate/todo-tutorial/README.md Installs project dependencies using pip and installs the project itself. ```bash pip install -r requirements.txt python setup.py install ``` -------------------------------- ### Install Cement Framework with CLI Extras Source: https://github.com/datafolklabs/cement/blob/main/README.md Install Cement with optional CLI extras, typically used for development purposes. This includes additional tools and dependencies for enhanced CLI development. ```bash pip install cement[cli] ``` -------------------------------- ### App.run Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/foundation.md Executes the application by wrapping setup and controller logic. It returns the result of the executed controller function if applicable, otherwise None. ```APIDOC ## App.run ### Description Executes the application by wrapping setup and controller logic. It returns the result of the executed controller function if applicable, otherwise None. ### Method `run() -> None | Any` ### Returns The result of the executed controller function if a base controller is set and a controller function is called, otherwise `None` if no controller dispatched or no controller function was called. ### Return type unknown ``` -------------------------------- ### Start Docker Services Source: https://github.com/datafolklabs/cement/blob/main/README.md Manually start all required Docker containers in detached mode. ```bash docker compose up -d ``` -------------------------------- ### Get and Instantiate a Handler Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/handler.md Demonstrates how to retrieve a specific handler by interface and label, instantiate it, set it up with the application, and then use its render method. ```python app = App() _handler = app.handler.get('output', 'json') output = _handler() output._setup(app) output.render(dict(foo='bar')) ``` -------------------------------- ### Dummy Mail Handler Send Method Examples Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/ext/ext_dummy.md Illustrates calling the send method of the DummyMailHandler. The first example uses all configuration defaults, while the second overrides them with specific arguments. ```python # Using all configuration defaults app.mail.send('This is my message body') ``` ```python # Overriding configuration defaults app.mail.send('My message body' to=['john@example.com'], from_addr='me@example.com', cc=['jane@example.com', 'rita@example.com'], subject='This is my subject', ) ``` -------------------------------- ### Generate Webapp with Defaults Source: https://github.com/datafolklabs/cement/blob/main/demo/generate-features/README.md Generates a web application using default settings for all features. Use this for a quick setup with pre-defined options. ```bash pdm run python myapp.py generate webapp /tmp/myproject --defaults ``` -------------------------------- ### Select Mode Prompt Example Source: https://github.com/datafolklabs/cement/blob/main/demo/generate-features/README.md Illustrates the user-facing prompt for a multi-valued feature in select mode, showing numbered options. ```text Web Framework 1: None — no web framework 2: Flask Web Framework 3: FastAPI Web Framework Enter the number for your selection: ``` -------------------------------- ### Debug Logging Example Source: https://github.com/datafolklabs/cement/blob/main/CLAUDE.md Use LOG.debug() for framework internals. Debug output is only shown when app.debug is True. ```python LOG.debug(f'hook {hook_spec[0]} not defined') ``` -------------------------------- ### Controller Meta-data: Arguments Example Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/ext/ext_argparse.md Demonstrates how to define arguments for a controller using the `arguments` attribute within the `Meta` class. This allows for custom help text and destination assignment for options. ```python class Base(ArgparseController): class Meta: label = 'base' arguments = [ (['-f', '--foo'], dict(help='my foo option', dest=foo)), ] def _post_argument_parsing(self): if self.app.pargs.foo: print('Got Foo Option Before Controller Dispatch') ``` -------------------------------- ### cement.utils.misc.minimal_logger Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/utils/misc.md Setup just enough for cement to be able to do debug logging. This is the logger used by the Cement framework. ```APIDOC ## cement.utils.misc.minimal_logger(namespace: str, debug: bool = False) -> MinimalLogger ### Description Setup just enough for cement to be able to do debug logging. This is the logger used by the Cement framework, which is setup and accessed before the application is functional. ### Parameters * **namespace** (str) - The logging namespace. This is generally `__name__` or anything you want. ### Keyword Arguments * **debug** (bool) - Toggle debug output. ### Returns A Logger object ### Return type object ### Example ```python from cement.utils.misc import minimal_logger LOG = minimal_logger('cement') LOG.debug('This is a debug message') ``` ``` -------------------------------- ### Sending Mail with Cement Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/mail.md Demonstrates how to send emails using the Cement mail handler. The first example uses all default configuration settings, while the second shows how to override these defaults with specific parameters. ```python app.mail.send('This is my message body') ``` ```python app.mail.send('My message body' to=['john@example.com'], from_addr='me@example.com', cc=['jane@example.com', 'rita@example.com'], subject='This is my subject', ) ``` -------------------------------- ### Dummy Mail Handler Example Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/ext/ext_dummy.md Demonstrates how to configure and use the DummyMailHandler in a Cement application. This handler prints email content to the console instead of sending it. ```python class MyApp(App): class Meta: label = 'myapp' mail_handler = 'dummy' with MyApp() as app: app.run() 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', ) ``` -------------------------------- ### Simple Prompt Example Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/utils/shell.md Use a simple prompt to halt operations and wait for user to press Enter. The 'default' parameter can be set to 'ENTER' to signify this behavior. ```python p = shell.Prompt("Press Enter To Continue", default='ENTER') ``` -------------------------------- ### Registering Custom Meta Defaults Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/foundation.md Example of how to register custom meta-defaults to override handler configurations, such as setting the JSON module for the JsonOutputHandler. ```python from cement import App META = { 'output.json': { 'json_module': 'ujson', } } class MyApp(App): class Meta: label = 'myapp' extensions = ['json'] meta_defaults = META ``` -------------------------------- ### List All Defined Interfaces Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/interface.md This snippet shows how to get a list of all interface labels that have been defined within the Cement application. This can be helpful for introspection or debugging. ```python app.interface.list() ``` -------------------------------- ### Alternative Module Mapping Example Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/foundation.md Demonstrates how to use `alternative_module_mapping` to replace standard Python modules with drop-in replacements, such as using `ujson` instead of `json`. The `App.__import__()` method is used to load these modules. ```python alternative_module_mapping = { 'json' : 'ujson', } _json = app.__import__('json') _json.dumps(data) ``` -------------------------------- ### cement.ext.ext_generate.Generate Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/ext/ext_generate.md Represents the Generate controller, inheriting from ArgparseController. It includes meta-options for configuration section, label, stacking behavior, and a setup method for application initialization. ```APIDOC ## Class: cement.ext.ext_generate.Generate ### Description Represents the Generate controller, inheriting from ArgparseController. It includes meta-options for configuration section, label, stacking behavior, and a setup method for application initialization. ### Class Hierarchy Bases: `ArgparseController` ### Meta Class #### Class: Meta Bases: `Meta` (`ArgparseController.Meta`) #### Attributes - **config_section** (string) - Defaults to 'generate'. A config section to merge config_defaults into. - **label** (string) - Defaults to 'generate'. The string identifier for the controller. - **stacked_on** (string) - Defaults to 'base'. A label of another controller to stack commands/arguments on top of. - **stacked_type** (string) - Defaults to 'nested'. Whether to embed commands and arguments within the parent controller’s namespace, or to nest this controller under the parent controller. Must be one of `['embedded', 'nested']`. ### Methods #### _setup(app: App) -> None Called during application initialization and must `setup` the handler object making it ready for the framework or the application to make further calls to it. - **Parameters:** - **app** (App instance) – The application object. ``` -------------------------------- ### Spawn a New Process Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/utils/shell.md Use shell.spawn_process() as a wrapper for multiprocessing.Process. By default, it calls start() before returning the process object. Arguments are passed to the target function. ```python from cement.utils import shell def add(a, b): print(a + b) p = shell.spawn_process(add, args=(12, 27)) p.join() ``` -------------------------------- ### Define Base and Second Controllers with Argparse Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/ext/ext_argparse.md Example of subclassing ArgparseController to define base and embedded controllers with custom arguments and help text. Ensure the application's arg_handler is set to 'argparse'. ```python from cement.ext.ext_argparse import ArgparseController class Base(ArgparseController): class Meta: label = 'base' description = 'description at the top of --help' epilog = "the text at the bottom of --help." arguments = [ ( ['-f', '--foo'], { 'help' : 'my foo option', 'dest' : 'foo' } ), ] class Second(ArgparseController): class Meta: label = 'second' stacked_on = 'base' stacked_type = 'embedded' arguments = [ ( ['--foo2'], { 'help' : 'my foo2 option', 'dest' : 'foo2' } ), ] ``` -------------------------------- ### Check if an Interface is Defined Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/interface.md This example demonstrates how to check if a specific interface, like 'log', is already defined and available in the application. This is useful for conditional logic or ensuring an interface exists before attempting to use it. ```python app.interface.defined('log') ``` -------------------------------- ### app.handler.setup Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/handler.md Sets up a handler class, preparing it for use. This method takes an uninstantiated handler class as input. ```APIDOC ## app.handler.setup ### Description Sets up a handler class so that it can be used by the application. ### Method POST ### Endpoint /handler/setup ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **handler_class** (type[Handler]) - Required - An uninstantiated handler class. ### Request Example ```python for controller in app.handler.list('controller'): ch = app.handler.setup(controller) ``` ### Response #### Success Response (200) - **Returns** (Handler) - The setup handler instance. #### Response Example None ``` -------------------------------- ### Build and Run Docker Image Source: https://github.com/datafolklabs/cement/blob/main/cement/cli/templates/generate/todo-tutorial/README.md Builds the Docker image for the TODO application and runs it, showing the help command. ```bash make docker docker run -it todo --help ``` -------------------------------- ### shell.spawn_process Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/utils/shell.md A wrapper around multiprocessing.Process, allowing for easy creation and starting of new processes. ```APIDOC ## shell.spawn_process ### Description A quick wrapper around `multiprocessing.Process()`. By default the `start()` function will be called before the spawned process object is returned. ### Parameters * **target** (function) – The target function to execute in the sub-process. * **args** – Additional arguments are passed to `Process()` * **kwargs** – Additional keyword arguments are passed to `Process()`. ### Keyword Arguments * **start** (bool) – Call `start()` on the process before returning the process object. Defaults to True. * **join** (bool) – Call `join()` on the process before returning the process object. Only called if `start == True`. Defaults to False. ### Returns The process object returned by `Process()`. ### Return type Process ``` -------------------------------- ### Build and Upload Project Distribution Source: https://github.com/datafolklabs/cement/blob/main/cement/cli/templates/generate/todo-tutorial/README.md Builds the project distribution and uploads it to PyPI using make commands. ```bash make dist make dist-upload ``` -------------------------------- ### spawn_thread Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/utils/shell.md A wrapper around threading.Thread() that allows for easy thread creation and optional immediate starting and joining. ```APIDOC ## spawn_thread ### Description A quick wrapper around `threading.Thread()`. By default, the `start()` function will be called before the spawned thread object is returned. See [Threading](https://docs.python.org/3/library/threading.html) for more information on the features of `Thread()`. ### Method Signature `cement.utils.shell.spawn_thread(target: Callable, start: bool = True, join: bool = False, *args: Any, **kwargs: Any) -> Thread` ### Parameters * **target** (*function*) – The target function to execute in the thread. * **args** – Additional arguments are passed to `Thread()`. * **kwargs** – Additional keyword arguments are passed to `Thread()`. ### Keyword Arguments * **start** (*bool*) – Call `start()` on the thread before returning the thread object. * **join** (*bool*) – Call `join()` on the thread before returning the thread object. Only called if `start == True`. ### Returns The thread object returned by `Thread()`. ### Return type object ### Example ```python from cement.utils import shell def add(a, b): print(a + b) t = shell.spawn_thread(add, args=(12, 27)) t.join() ``` ``` -------------------------------- ### App.validate_config Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/foundation.md Validates the application's configuration settings. Includes an example of checking and creating log directories. ```APIDOC ## App.validate_config ### Description Validates the application's configuration settings. Includes an example of checking and creating log directories. ### Example ```python import os from cement import App class MyApp(App): class Meta: label = 'myapp' def validate_config(self): super(MyApp, self).validate_config() # test that the log file directory exist, if not create it from pathlib import Path logdir = Path(self.config.get('log', 'file')).parent if not logdir.exists(): logdir.mkdir(parents=True) ``` ``` -------------------------------- ### Module-Level Logger Initialization Source: https://github.com/datafolklabs/cement/blob/main/CLAUDE.md Initialize a module-level logger using the minimal_logger function. No complex logging.config setup is required. ```python LOG = minimal_logger(__name__) ``` -------------------------------- ### HandlerManager Class Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/handler.md Manages the handler system, allowing for defining, getting, and resolving handlers within the Cement Framework. ```APIDOC ## Class cement.core.handler.HandlerManager ### Description Manages the handler system to define, get, resolve, etc handlers with the Cement Framework. ### Methods #### get(interface: str, handler_label: str, fallback: type[Handler] | None = None, **kwargs: Any) -> Handler | type[Handler] Get a handler object. * **Parameters:** * **interface** (str) – The interface of the handler (e.g., `output`). * **handler_label** (str) – The label of the handler (e.g., `json`). * **fallback** (type[Handler] | None) – A fallback value to return if `handler_label` doesn’t exist. * **Keyword Arguments:** **setup** (bool) – Whether or not to call `setup()` on the handler before returning. * **Returns:** An uninstantiated handler object. * **Raises:** [**cement.core.exc.InterfaceError**](exc.md#cement.core.exc.InterfaceError) – If the `interface` or handler does not exist. ### Example ```python _handler = app.handler.get('output', 'json') output = _handler() output._setup(app) output.render(dict(foo='bar')) ``` #### list(interface: str) -> list[type[Handler]] Return a list of handlers for a given `interface`. * **Parameters:** **interface** (str) – The interface of the handler (e.g., `output`). * **Returns:** Handler labels (str) that match `interface`. * **Raises:** [**cement.core.exc.InterfaceError**](exc.md#cement.core.exc.InterfaceError) – If the `interface` does not exist. ``` -------------------------------- ### Run Cement CLI Application Source: https://github.com/datafolklabs/cement/blob/main/cement/cli/templates/generate/project/README.md Execute the Cement CLI application with help command using PDM. ```bash pdm run {{ label }} --help ``` -------------------------------- ### Run Cement Commands with Devbox Source: https://github.com/datafolklabs/cement/blob/main/README.md Execute Cement commands, such as displaying help information, using this command. ```bash pdm run cement --help ``` -------------------------------- ### Handler Class Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/handler.md The base Handler class that all Cement Handlers should subclass. It defines meta-data and setup methods for handler initialization. ```APIDOC ## Class cement.core.handler.Handler ### Description Base handler class that all Cement Handlers should subclass from. ### Meta Class #### config_defaults: dict[str, Any] | None Default configuration dictionary merged into the application's config. #### config_section: str | None Configuration section to merge `config_defaults` with. #### interface: str The interface that this class implements. #### label: str The string identifier of this handler. #### overridable: bool Whether or not the handler can be overridden. ### Methods #### _setup(app: App) -> None Called during application initialization to set up the handler. * **Parameters:** **app** (instance) – The application object. #### _validate() -> None Perform validation to ensure proper data and meta-data. ``` -------------------------------- ### _lay_cement Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/foundation.md Initializes the framework. This is an internal method. ```APIDOC ## _lay_cement ### Description Initialize the framework. This is an internal method and not intended for direct user invocation. ### Method N/A (Internal Method) ### Endpoint N/A (Internal Method) ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Execute Bash Shell in Docker Container Source: https://github.com/datafolklabs/cement/blob/main/README.md Access the 'cement' development container via a BASH shell after starting Docker services. ```bash docker compose exec cement /bin/bash ``` -------------------------------- ### Build Docker Image Source: https://github.com/datafolklabs/cement/blob/main/cement/cli/templates/generate/project/README.md Build the Docker image for the Cement project using the Makefile. ```bash make docker ``` -------------------------------- ### Headless Run with --defaults Source: https://github.com/datafolklabs/cement/blob/main/demo/generate-features/README.md Demonstrates how to run a feature generation command with default values using the --defaults flag. ```bash pdm run python myapp.py generate webapp /tmp/myproject --defaults # → web_framework = "none" (feature-level default) # → requirements.txt and wsgi.py both ignored (not rendered) ``` -------------------------------- ### Function Annotation Example Source: https://github.com/datafolklabs/cement/blob/main/CLAUDE.md Always annotate function parameters and return types. Use TYPE_CHECKING for deferred imports to prevent circular dependencies. ```python def send(self, msg: str, **kw: Any) -> Dict[str, Any]: ``` -------------------------------- ### Spawn and Join a Thread Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/utils/shell.md Demonstrates how to use `shell.spawn_thread` to create a new thread that executes a target function with arguments, and then waits for the thread to complete using `join()`. ```python from cement.utils import shell def add(a, b): print(a + b) t = shell.spawn_thread(add, args=(12, 27)) t.join() ``` -------------------------------- ### cement.utils.misc.init_defaults Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/utils/misc.md Returns a standard dictionary object to use for application defaults. If sections are given, it will create a nested dict for each section name. ```APIDOC ## cement.utils.misc.init_defaults(*sections: str) -> dict[str, Any] ### Description Returns a standard dictionary object to use for application defaults. If sections are given, it will create a nested dict for each section name. ### Parameters * **sections** (str) - Section keys to create nested dictionaries for. ### Returns Dictionary of nested dictionaries (sections) ### Return type dict ### Example ```python from cement import App, init_defaults defaults = init_defaults('myapp', 'section2', 'section3') defaults['myapp']['debug'] = False defaults['section2']['foo'] = 'bar' defaults['section3']['foo2'] = 'bar2' app = App('myapp', config_defaults=defaults) ``` ``` -------------------------------- ### Enter Development Container with Docker Source: https://github.com/datafolklabs/cement/blob/main/README.md This command creates all required Docker containers and launches a BASH shell within the 'cement' development container. ```bash make dev |> cement <| src # ``` -------------------------------- ### Initialize Application Defaults Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/utils/misc.md Use init_defaults to create a standard dictionary for application defaults, optionally with nested sections. This is useful for setting up configurations, especially in testing scenarios. ```python from cement import App, init_defaults defaults = init_defaults('myapp', 'section2', 'section3') defaults['myapp']['debug'] = False defaults['section2']['foo'] = 'bar' defaults['section3']['foo2'] = 'bar2' app = App('myapp', config_defaults=defaults) ``` -------------------------------- ### Run Cement CLI from Docker Source: https://github.com/datafolklabs/cement/blob/main/cement/cli/templates/generate/project/README.md Run the Cement CLI application from a Docker container and display help. ```bash docker run -it {{ label }} --help ``` -------------------------------- ### Run Tests and Coverage Source: https://github.com/datafolklabs/cement/blob/main/cement/cli/templates/generate/project/README.md Execute tests and coverage reports using the Makefile. ```bash make test ``` -------------------------------- ### Get an Output Interface Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/interface.md Retrieve an uninstantiated interface class, such as the 'output' interface, using its string label. This allows you to access the interface's methods or properties. ```python i = app.interface.get('output') ``` -------------------------------- ### ConfigInterface Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/config.md Defines the Config Interface for configuration handlers. Implementations should provide methods for adding sections, getting and setting configuration values, and managing the configuration structure. ```APIDOC ## class cement.core.config.ConfigInterface ### Description This class defines the Config Interface. Handlers that implement this interface must provide the methods and attributes defined below. In general, most implementations should sub-class from the provided `ConfigHandler` base class as a starting point. ### Methods #### add_section(section: str) -> None ##### Description Add a new section if it doesn’t already exist. ##### Parameters * **section** (str) - The section label to create. #### get(section: str, key: str) -> Any ##### Description Return a configuration value based on `section.key`. Must honor environment variables if they exist to override the config… for example `config['myapp']['foo']['bar']` must be overridable by the environment variable `MYAPP_FOO_BAR`…. Note that `MYAPP_` must prefix all vars, therefore `config['redis']['foo']` would be overridable by `MYAPP_REDIS_FOO` … but `config['myapp']['foo']['bar']` would not have a double prefix of `MYAPP_MYAPP_FOO_BAR`. ##### Parameters * **section** (str) - The section of the configuration to pull key values from. * **key** (str) - The configuration key to get the value for. ##### Returns The value of the `key` in `section`. #### get_dict() -> dict[str, Any] ##### Description Return a dict of the entire configuration. ##### Returns A dictionary of the entire config. #### get_section_dict(section: str) -> dict[str, Any] ##### Description Return a dict of configuration parameters for `section`. ##### Parameters * **section** (str) - The config section to generate a dict from (using that sections’ keys). ##### Returns A dictionary of the config section. #### get_sections() -> list[str] ##### Description Return a list of configuration sections. ##### Returns A list of config sections. #### has_section(section: str) -> bool ##### Description Returns whether or not the section exists. ##### Parameters * **section** (str) - The section to test for. ##### Returns `True` if the configuration section exists, `False` otherwise. #### keys(section: str) -> list[str] ##### Description Return a list of configuration keys from `section`. ##### Parameters * **section** (list) - The config section to pull keys from. ##### Returns A list of keys in `section`. #### merge(dict_obj: dict, override: bool = True) -> None ##### Description Merges a dict object into the configuration. ##### Parameters * **dict_obj** (dict) - The dictionary to merge into the config * **override** (bool) - Whether to override existing values or not. #### parse_file(file_path: str) -> bool ##### Description Parse config file settings from `file_path`. Returns True if the file existed, and was parsed successfully. Returns False otherwise. ##### Parameters * **file_path** (str) - The path to the config file to parse. ##### Returns `True` if the file was parsed, `False` otherwise. #### set(section: str, key: str, value: Any) -> None ##### Description Set a configuration value based at `section.key`. ##### Parameters * **section** (str) - The `section` of the configuration to pull key value from. * **key** (str) - The configuration key to set the value at. * **value** - The value to set. ``` -------------------------------- ### cement.core.meta.MetaMixin Class Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/meta.md The MetaMixin class is a mixin that provides meta class support to add settings to instances of objects. It enforces a rule that meta keys cannot start with an underscore. ```APIDOC ## cement.core.meta.MetaMixin Class ### Description Mixin that provides the meta class support to add settings to instances of objects. Meta keys cannot start with a `_`. ### Class cement.core.meta.MetaMixin ### Parameters #### Arguments - **args** (Any) - Positional arguments. - **kwargs** (Any) - Keyword arguments. ``` -------------------------------- ### Get Absolute Path with Tilde Expansion Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/utils/fs.md Use fs.abspath to convert a relative path to an absolute path, also expanding the '~' shortcut for the user's home directory. ```python from cement.utils import fs fs.abspath('~/some/path') fs.abspath('./some.file') ``` -------------------------------- ### Default App Meta Configuration Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/foundation.md Illustrates the default configuration for `App.Meta.config_dirs` and `App.Meta.config_files` based on the application's label. These settings define where Cement searches for configuration files and extensions. ```python [ '/etc/myapp/ext.d/', '/etc/myapp/plugins.d/', '~/.myapp/config/ext.d/', '~/.myapp/config/plugins.d/', ] ``` ```python [ '/etc/myapp/myapp.conf', '~/.config/myapp/myapp.conf', '~/.myapp.conf', ] ``` -------------------------------- ### Dummy Mail Handler Configuration Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/ext/ext_dummy.md Shows how to configure the DummyMailHandler using a configuration file. Default mail settings like 'to', 'from_addr', 'cc', 'bcc', and 'subject' can be specified. ```text [myapp] # set the mail handler to use mail_handler = dummy [mail.dummy] # 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 > ``` -------------------------------- ### Spawn Process or Thread with Target Function Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/utils/shell.md Use shell.spawn() to wrap multiprocessing.Process or multiprocessing.Thread. It allows specifying whether to start, join, or execute as a thread. Additional arguments are passed to the target function. ```python from cement.utils import shell def add(a, b): print(a + b) p = shell.spawn(add, args=(12, 27)) p.join() ``` -------------------------------- ### Project Structure with FastAPI Enabled Source: https://github.com/datafolklabs/cement/blob/main/demo/generate-features/README.md Enabling the FastAPI web framework includes additional files such as requirements.txt and wsgi.py. The requirements.txt file will specify the FastAPI version. ```text /tmp/myproject/ ├── .dockerignore ├── Dockerfile ├── README.md ├── app.py ├── docker-compose.yml ├── requirements.txt └── wsgi.py ``` -------------------------------- ### app.handler.resolve Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/handler.md Resolves the actual handler instance. It can accept the handler by its label (string), as an instantiated object, or as a non-instantiated class. Optional arguments allow for error handling, default meta-data, and setup execution. ```APIDOC ## app.handler.resolve ### Description Resolves the actual handler instance based on the provided interface and handler definition. The handler definition can be a string label, an instantiated object, or a non-instantiated class. ### Method GET ### Endpoint /handler/resolve ### Parameters #### Path Parameters None #### Query Parameters - **interface** (str) - Required - The interface of the handler (e.g., `output`). - **handler_def** (str | Handler | type[Handler]) - Required - The loose reference of the handler, by label, instantiated object, or non-instantiated class. - **raise_error** (bool) - Optional - Whether or not to raise an exception if unable to resolve the handler. Default: `False`. - **meta_defaults** (dict) - Optional - Optional meta-data dictionary used as defaults to pass when instantiating uninstantiated handlers. Use `App.Meta.meta_defaults` by default. - **setup** (bool) - Optional - Whether or not to call `.setup()` before return. Default: `False`. #### Request Body None ### Request Example ```python # via label (str) log = app.handler.resolve('log', 'colorlog') # via uninstantiated handler class log = app.handler.resolve('log', ColorLogHanddler) # via instantiated handler instance log = app.handler.resolve('log', ColorLogHandler()) ``` ### Response #### Success Response (200) - **Returns** (Handler) - The instantiated handler object. #### Response Example ```json { "handler_instance": "" } ``` ``` -------------------------------- ### Configure PyPI Credentials Source: https://github.com/datafolklabs/cement/blob/main/cement/cli/templates/generate/todo-tutorial/README.md Configures PyPI login credentials in the ~/.pypirc file. Replace YOUR_USERNAME and YOUR_PASSWORD with actual credentials. ```ini [pypi] username = YOUR_USERNAME password = YOUR_PASSWORD ``` -------------------------------- ### cement.utils.fs.abspath Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/utils/fs.md Returns an absolute path, while also expanding the `~` user directory shortcut. ```APIDOC ## cement.utils.fs.abspath ### Description Return an absolute path, while also expanding the `~` user directory shortcut. ### Parameters: * **path** (*str*) – The original path to expand. ### Returns: The fully expanded, absolute path to the given `path` ### Return type: str ### Example: ```python from cement.utils import fs fs.abspath('~/some/path') fs.abspath('./some.file') ``` ``` -------------------------------- ### cement.core.backend Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/index.md Core backend module. ```APIDOC ## Module: cement.core.backend ### Description Core backend module. No specific classes or functions are detailed here, refer to backend.md for more information. ``` -------------------------------- ### cement.core.config Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/index.md Provides classes for configuration management, including ConfigHandler and ConfigInterface. ```APIDOC ## Module: cement.core.config ### Description Provides classes for configuration management. ### Classes - **ConfigHandler**: Handles application configuration. - **ConfigInterface**: Interface for configuration handlers. ``` -------------------------------- ### Upload Distribution to PyPI Source: https://github.com/datafolklabs/cement/blob/main/cement/cli/templates/generate/project/README.md Upload the built distribution package to PyPI using the Makefile. ```bash make dist-upload ``` -------------------------------- ### Build Distribution for PyPI Source: https://github.com/datafolklabs/cement/blob/main/cement/cli/templates/generate/project/README.md Build the distribution package for PyPI using the Makefile. ```bash make dist ``` -------------------------------- ### Run Core Tests using Makefile on Windows Source: https://github.com/datafolklabs/cement/blob/main/README.md Executes the core library tests using a Makefile target. This provides an alternative to the direct pdm command for running tests on Windows. ```bash make test-core ``` -------------------------------- ### App.render Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/core/foundation.md Renders data using a specified template and output handler. It's a wrapper around `self.output.render()` and returns an empty string if no output handler is defined. ```APIDOC ## App.render ### Description Renders data using a specified template and output handler. It's a wrapper around `self.output.render()` and returns an empty string if no output handler is defined. ### Method `render(data: Any, template: str | None = None, out: IO = <_io.TextIOWrapper name='' mode='w' encoding='utf-8'>, handler: str | None = None, **kw: Any) -> str` ### Parameters #### Arguments - **data** (dict) – The data dictionary to render. - **kw** (dict) – Additional keyword arguments will be passed to the output handler when calling `self.output.render()`. #### Keyword Arguments - **template** (str) – The template to render to (note that some output handlers do not use templates). - **out** (IO) – A file like object (i.e. `sys.stdout`, or actual file). Set to `None` if no output is desired (just render and return). Default is `sys.stdout`, however if `App.quiet` is `True`, this will be set to `None`. - **handler** (str) – The output handler to use to render. Defaults to `App.Meta.output_handler`. ``` -------------------------------- ### Migrate CEMENT_FRAMEWORK_LOGGING to CEMENT_LOG Source: https://github.com/datafolklabs/cement/blob/main/DEPRECATIONS.md Use the CEMENT_LOG environment variable instead of CEMENT_FRAMEWORK_LOGGING. This applies to runtime logging configuration. ```bash # Before export CEMENT_FRAMEWORK_LOGGING=true # After export CEMENT_LOG=true ``` -------------------------------- ### cement.ext.ext_daemon.extend_app Source: https://github.com/datafolklabs/cement/blob/main/docs/source/api/ext/ext_daemon.md Extends the application object by adding the `--daemon` argument and setting default configuration options for the daemon section. ```APIDOC ### cement.ext.ext_daemon.extend_app(app: [App](../core/foundation.md#cement.core.foundation.App)) -> None #### Description Adds the `--daemon` argument to the argument object, and sets the default `[daemon]` config section options. #### Parameters - **app** ([App](../core/foundation.md#cement.core.foundation.App)) - The application instance. ``` -------------------------------- ### List Open Issues Source: https://github.com/datafolklabs/cement/blob/main/CLAUDE.md Use the gh CLI to list open issues for the datafolklabs/cement repository. ```bash gh issue list -R datafolklabs/cement ```