{"id":37070795,"url":"https://github.com/scitrera/python-app-framework","last_synced_at":"2026-01-14T08:16:12.545Z","repository":{"id":268165760,"uuid":"872621997","full_name":"scitrera/python-app-framework","owner":"scitrera","description":null,"archived":false,"fork":false,"pushed_at":"2025-09-28T15:42:24.000Z","size":167,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-09-29T13:16:42.968Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/scitrera.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-10-14T19:02:09.000Z","updated_at":"2025-09-28T15:42:27.000Z","dependencies_parsed_at":"2024-12-14T20:46:48.829Z","dependency_job_id":"95e26b8c-3f4b-42a7-b6b2-d6cd035ccae8","html_url":"https://github.com/scitrera/python-app-framework","commit_stats":null,"previous_names":["scitrera/python-app-framework"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/scitrera/python-app-framework","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scitrera%2Fpython-app-framework","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scitrera%2Fpython-app-framework/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scitrera%2Fpython-app-framework/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scitrera%2Fpython-app-framework/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/scitrera","download_url":"https://codeload.github.com/scitrera/python-app-framework/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scitrera%2Fpython-app-framework/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28413746,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-14T05:26:33.345Z","status":"ssl_error","status_checked_at":"2026-01-14T05:21:57.251Z","response_time":107,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-01-14T08:16:11.741Z","updated_at":"2026-01-14T08:16:12.532Z","avatar_url":"https://github.com/scitrera.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# scitrera-app-framework\n\nCommon code and utilities for Scitrera applications and container images.\n\nThis package provides a lightweight application framework for Python services, CLIs, and desktop apps. It centers on a\nsmall environment/variables abstraction, structured logging, a simple plugin system, optional stateful working\ndirectories, and helper utilities for background execution, multi‑tenant configuration, and integration with external\ntools like Pyroscope.\n\n\u003e Note: This repository is being gradually opened and updated. Expect incremental improvements and additional docs\n\u003e as code is moved from private projects.\n\n## Stack and Packaging\n\n- Language: Python (\u003e= 3.9)\n- Dependencies (runtime):\n    - botwinick-utils (\u003e= 0.0.20)\n    - vpd\n    - python-json-logger (\u003c 3.0.0)\n- Optional/dev dependencies:\n    - python-dotenv (for loading .env files via `add_env_file_source`)\n\n## Overview\n\nKey capabilities:\n\n- Variables and configuration abstraction with layered sources and ergonomic access.\n- Structured logging integration with simple JSON formatting option.\n- Plugin and extension registry supporting both single and multi-extension modes.\n- Optional stateful working directory management (e.g., for containerized or desktop apps).\n- Background execution plugin backed by thread pool.\n- Optional profiling integration via Pyroscope plugin.\n- Multi-tenant configuration helper with pluggable provider.\n- Convenience utilities for desktop apps and test harnesses.\n\n## Requirements\n\n- Python 3.9+\n- OS: Windows, macOS, Linux (framework is OS-independent; some optional pieces may differ by platform)\n\n## Installation\n\nChoose one of the following:\n\n- From source (editable):\n    - `pip install -e .`\n    - or install runtime deps only: `pip install -r requirements.txt`\n\n- From PyPI:\n    - `pip install scitrera-app-framework`\n\n## Quick Start\n\nInitialize the framework at the start of your program and get a logger:\n\n```python\nfrom scitrera_app_framework import init_framework, get_logger\n\nif __name__ == '__main__':\n    v = init_framework('my-app', log_level='INFO')\n    logger = get_logger(v)\n    logger.info('Hello from SAF!')\n\n    logger2 = get_logger(v, name='child')\n    logger2.info('Hello from SAF child logger!')\n```\n\nEnable base plugins (e.g., background execution) and submit a job:\n\n```python\nfrom scitrera_app_framework import init_framework, get_extension\nfrom scitrera_app_framework.base_plugins import EXT_BACKGROUND_EXEC\n\ninit_framework('my-app', base_plugins=True)\nget_extension(EXT_BACKGROUND_EXEC).submit_job(print, 'background task')\n```\n\nMulti-tenant example:\n\n```python\nfrom scitrera_app_framework import init_framework, get_logger\nfrom scitrera_app_framework.ext_plugins.muti_tenant import get_tenant_variables\n\nv = init_framework('my-app', log_level='DEBUG', multitenant=True)\n\n# Obtain per-tenant Variables and a logger\ntenant_v = get_tenant_variables('tenant1', v=v)\ntenant_logger = get_logger(tenant_v)\ntenant_logger.info('tenant-specific log')\n```\n\nList plugins for a multi-extension point (from tests):\n\n```python\nfrom scitrera_app_framework import init_framework, register_plugin, get_extensions\nfrom scitrera_app_framework.api import Plugin, Variables\n\nEXT = 'example-ext'\n\n\nclass ImplA(Plugin):\n    def extension_point_name(self, v: Variables):\n        return EXT\n\n    def is_multi_extension(self, v: Variables):\n        return True\n\n    def initialize(self, v, logger):\n        return 'A'\n\n\nclass ImplB(ImplA):\n    def initialize(self, v, logger):\n        return 'B'\n\n\ninit_framework('my-app')\nregister_plugin(ImplA)\nregister_plugin(ImplB)\nprint(get_extensions(EXT))  # ['A', 'B']\n```\n\n## Entry Points and Scripts\n\n- Primary usage is as a Python library you import into your own application.\n- Utilities under `scitrera_app_framework/slaunch/` provide helpers for launching and managing environments (e.g.,\n  conda), but are not wired as direct CLIs. You can import and call functions like `slaunch.main.launch_app(...)` from\n  your code.\n\n## Key Modules and APIs\n\n- `scitrera_app_framework.init_framework(...)`: main initialization; sets up logging, stateful paths, and shutdown hooks\n  based on env/kwargs.\n- `init_framework_desktop(...)`: desktop-friendly defaults (e.g., use `~/.config/\u003cAPP_NAME\u003e` and atexit hooks).\n- `init_framework_test_harness(...)`: testing-friendly defaults (DEBUG logging, no shutdown hooks/stateful).\n- `init_framework_embedded(...)`: use when embedding within larger apps; avoids overriding external logging.\n- `get_logger(v=None, name=None)`: get the main or child logger.\n- `get_working_path(v=None, default='.', env_key='DATA_WORKING_PATH')`: resolve a working path from env/stateful.\n- Plugin system:\n    - `register_plugin(PluginType, v=None, init=False)`\n    - `get_extension(ext_name_or_type, v=None)` for single extension\n    - `get_extensions(ext_name_or_type, v=None)` for multi-extension\n    - Built-ins:\n        - Background executor: `EXT_BACKGROUND_EXEC` and `get_background_exec()`\n        - Pyroscope profiling: `ext_plugins.pyroscope_plugin.PyroscopePlugin`\n        - Multi-tenant: `ext_plugins.muti_tenant.MultiTenantPlugin`\n- Env file support: `scitrera_app_framework.core.util.add_env_file_source(\".env\")` (requires `python-dotenv`).\n\n## Environment Variables\n\nCommon environment variables recognized by the framework and plugins:\n\nCore and logging:\n\n- `APP_NAME`: Override computed application name.\n- `BUILD_IMAGE_NAME`: Image name for logging context (default: base app name).\n- `BUILD_CONTAINER_VERSION`: Version string (default: `DEV`).\n- `LOGGING_LEVEL`: Log level (default from `init_framework(log_level=...)`).\n- `LOGGING_FORMAT`: `'json'` for JSON logs or a Python `%`-format string. Otherwise uses a sensible default.\n- `LOGGING_DATE_FORMAT`: Date/time format string.\n- `SAF_ENABLE_PYTHON_FAULT_HANDLER`: Enable Python `faulthandler` (default True unless overridden by `init_framework`).\n- `SAF_INSTALL_SHUTDOWN_HOOKS`: Install shutdown hooks (default True unless overridden).\n- `SAF_SHUTDOWN_HOOK_VIA_ATEXIT`: Prefer atexit-based hooks (default depends on context; `init_framework_desktop` uses\n  True).\n\nStateful and paths:\n\n- `SAF_SETUP_STATEFUL`: Enable stateful working directory setup (default True unless overridden).\n- `STATEFUL_ROOT`: Root directory for stateful data (default: `./scratch` unless overridden by `init_framework`).\n- `RUN_ID`: Used in stateful path composition.\n- `RUN_SERIAL`: Used in stateful path composition; may be auto-set when `SAF_STATEFUL_SERIAL_STRATEGY=ms`.\n- `SAF_STATEFUL_CHDIR`: Change working directory into the stateful path (default True for base; False in desktop\n  helper).\n- `SAF_STATEFUL_SERIAL_STRATEGY`: e.g., `ms` to use current time in milliseconds.\n- `DATA_WORKING_PATH`: When set, overrides `get_working_path()` resolution.\n\nBackground executor plugin:\n\n- `SAF_JOB_THREADS`: Max worker threads (default from botwinick-utils).\n- `SAF_JOB_COLLISIONS_INFO`: Log job collisions as info (default False).\n\nPyroscope plugin:\n\n- `PYROSCOPE_ENABLED`: Enable plugin (also controllable via `init_framework(pyroscope=True)` defaulting).\n- `PYROSCOPE_SERVER`: Server address (default `http://pyroscope.pyroscope.svc:4040`).\n- `PYROSCOPE_USER`: Basic auth user (default empty).\n- `PYROSCOPE_TOKEN`: Basic auth password/token (default empty).\n- `PYROSCOPE_TENANT`: Tenant ID (default empty).\n- `PYROSCOPE_SAMPLE_RATE`: Sample rate (int, default 100).\n- `PYROSCOPE_DETECT_SUBPROCESSES`: Detect subprocesses (bool, default True).\n- `PYROSCOPE_ON_CPU`: CPU profiling (bool, default True).\n- `PYROSCOPE_GIL_ONLY`: GIL-only profiling (bool, default True).\n- `PYROSCOPE_ENABLE_LOGGING`: Enable Pyroscope client logging (bool, default False).\n- `PYROSCOPE_TAG_*`: Any variables with this prefix are turned into Pyroscope tags.\n\nMulti-tenant plugin:\n\n- `SAF_MULTITENANT_ENABLED`: Enable multi-tenant plugin.\n- `SAF_MULTITENANT_PROVIDER`: Python import path for provider type (default is the built-in `BaseMultiTenantProvider`).\n- `SAF_MULTITENANT_INCLUDE_ENV`: If True, include process env in tenant Variables placement (EnvPlacement.BOTTOM).\n\n## Slaunch utilities (conda/python helpers)\n\nLocated under `scitrera_app_framework/slaunch/` with functions for:\n\n- Creating and updating conda environments (apply conda/pip requirements).\n- Launching apps with manifests of libs/apps and self-update support.\n- Windows/macOS/Linux support via platform detection.\n\nThese are utility functions intended to be imported and used by your own launcher scripts. There is no direct CLI entry\npoint defined in this package.\n\n## Kubernetes utilities (k8s.util)\n\nThe module `scitrera_app_framework.k8s.util` contains small, practical helpers for working with Kubernetes objects. These are useful when building simple operators or orchestrating activities from Python in a K8s environment.\n\n- Completely optional and separate from the core framework; nothing depends on them by default.\n- Requires the Kubernetes Python client (and uses utilities from `vpd`). Install with: `pip install kubernetes`.\n- Functions work with either plain dicts (YAML loaded) or Kubernetes client objects where noted.\n\nHighlights:\n- `apply_yaml_object(obj, verb='apply'|'get'|'replace')`: Apply/get/replace a K8s object (TODO: describe server-side vs client-side apply).\n- `parse_yaml(path_or_text)`: Parse YAML into Python objects (dicts). Handy for loading manifests.\n- `start_pod(pod_def, wait=True, replace=False, wait_delay=0.25, wait_until_terminated=False)`: Create or replace a Pod and optionally wait until Running (or Terminated).\n- `is_pod_running(pod_def, strict=False)`: Check if a Pod is Running (or Pending when `strict=False`).\n- `is_pod_in_terminated_state(pod_def)`: Check if a Pod finished (Succeeded or Failed).\n- `pod_exists(pod_def)`: Determine if a Pod currently exists.\n- `get_pod_env(pod_def, container_name=None, container_index=0)`: Get a reference to a container's `env` list for in-place edits.\n- `merge_env_vars(env, *complex_items, key_upper=True, **fixed_pairs)`: Merge environment variable definitions (supports complex `valueFrom` entries and simple key=value pairs). Modifies list in-place.\n- `fixed_env_vars(**pairs)`: Build fixed env var entries from kwargs.\n- `get_metadata_name(obj)`, `get_metadata_namespace(obj)`: Extract metadata fields from dicts or client objects.\n- `get_headless_service_dns_name_for_pod(pod_def, svc_def)`: Compose the DNS name `\u003cpod\u003e.\u003cservice\u003e.\u003cnamespace\u003e.svc` for a headless Service.\n\nExample: launch a Pod from YAML and wait until it runs\n\n```python\nfrom scitrera_app_framework.k8s.util import parse_yaml, start_pod, is_pod_running\n\npod = parse_yaml('pod.yaml')\nstart_pod(pod, wait=True)\nprint('running?', is_pod_running(pod, strict=True))\n```\n\nExample: add env vars to the first container of a Pod manifest before applying\n\n```python\nfrom scitrera_app_framework.k8s.util import parse_yaml, get_pod_env, merge_env_vars, apply_yaml_object\n\npod = parse_yaml('pod.yaml')\nenv = get_pod_env(pod)\nmerge_env_vars(env, { 'name': 'CONFIG_PATH', 'valueFrom': { 'configMapKeyRef': { 'name': 'my-cm', 'key': 'cfg' } } },\n                IMAGE_TAG='v1.2.3', DEBUG=True)\napply_yaml_object(pod)  # apply modified manifest\n```\n\nNote: These helpers assume your local environment is configured to talk to a cluster (e.g., `KUBECONFIG` or in-cluster config).\n\n## Project Structure\n\n- `scitrera_app_framework/` – Library code\n    - `api/` – Variables and Plugin base types\n    - `core/` – Initialization, logging, stateful paths, plugin registry (not intended to be used directly by users)\n    - `base_plugins/` – Built-in optional plugins (e.g., background executor)\n    - `ext_plugins/` – Optional extensions (e.g., Pyroscope, Multi-tenant)\n    - `k8s/` - Optional Kubernetes Utilities\n    - `slaunch/` – \"slaunch\" is a white-label ready set of utilities to maintain structured conda environments and applications with auto-updating on start, etc.\n    - `util/` – Miscellaneous helpers (async, parsing, imports)\n- `setup.py` – Build configuration\n- `requirements.txt` – Development/runtime dependencies list\n- `LICENSE.txt` – BSD 3‑Clause license text\n\n## License\n\nBSD 3‑Clause License. See `LICENSE.txt` for details.\n\n## Contributing\n\n- Issues and PRs are welcome. Please keep changes small and focused.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fscitrera%2Fpython-app-framework","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fscitrera%2Fpython-app-framework","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fscitrera%2Fpython-app-framework/lists"}