Skip to main content

SJI

Eine einfache Python-Bibliothek für die Initialisierung von Jobs/Skripten (Logging, Konfiguration, Ordnerstruktur).

Installation

pip install sji

Verwendung

from sji import (
  SimpleJobInit,
  get_script_version,
  apply_credential_placeholders_from_file,
)
import configparser

# __file__ an SimpleJobInit übergeben
sj = SimpleJobInit(__file__)

# Logger verwenden
sj.logger.info("Starte Job...")

# Konfiguration lesen (INI)
cfg = sj.config
value = cfg.get('section', 'key', fallback='default')

# Persistente Datei-Pfade erhalten
csv_path = sj.get_persistent_file_path('csv')

# Temporäre Datei-Pfade erhalten
tmp_path = sj.get_tmp_file_path('work.tmp')

# Versionen ermitteln
sj.logger.info(f"script_version={sj.get_job_script_version(include_git_tag=True)}")
sj.logger.info(f"config_file_hash={sj.get_config_file_hash()}")
sj.logger.info(f"config_file_version={sj.get_config_file_version()}")

# Top-Level-Funktion (unabhängig von der Klasse):
script_version = get_script_version(__file__, include_git_tag=True)

# Konfiguration mit Maskierung loggen
sj.log_config(secret_fields={"db_config": ["password", "db_password"], "api": ["api_key", "token"]})

# Optional: Credential-Ersetzung auch für extern geladene Configs nutzen
external_cfg = configparser.ConfigParser()
external_cfg.read("path/to/other.config.ini")
replaced_fields = apply_credential_placeholders_from_file(
  config=external_cfg,
  credentials_filepath="path/to/other.credentials.ini",
  logger=sj.logger,
)

Dabei werden automatisch erzeugt/genutzt:

  • logs/.log (mit optionaler Rotation)
  • tmp/ Verzeichnis
  • .config.ini für Einstellungen

Minimalbeispiel für die INI-Datei

Datei: <skriptname>.config.ini im selben Verzeichnis wie das Skript

[logging]
level = INFO
log_rotation_when = midnight
log_rotation_backup_count = 7

[section]
key = some-value

Credential-Ersetzung

SJI unterstützt die automatische Ersetzung von Platzhaltern in der Konfigurationsdatei durch Werte aus einer separaten credentials.ini-Datei. Dies ermöglicht es, sensible Daten wie Passwörter oder API-Schlüssel getrennt von der Hauptkonfiguration zu verwalten.

Funktionsweise

  1. Platzhalter-Format: In der config.ini können Platzhalter im Format [[[[name]]]] verwendet werden.
  2. Credentials-Datei: Die Datei <skriptname>.credentials.ini wird automatisch im selben Verzeichnis wie das Skript gesucht.
  3. Ersetzung: Platzhalter werden durch Werte aus derselben Section und mit demselben Key-Namen aus der credentials.ini ersetzt.
  4. Optional: Wenn die credentials.ini nicht existiert, bleiben die Platzhalter unverändert.

Beispiel

test_job.config.ini:

[db_config]
db_user = postgres
db_password = [[[[db_password]]]]
db_host = localhost
db_port = 5432
db_name = test_db

[api]
api_key = [[[[api_key]]]]

test_job.credentials.ini:

[db_config]
db_password = my_secret_password_123

[api]
api_key = api_key_abc123xyz

Nach der Initialisierung von SimpleJobInit werden die Platzhalter automatisch ersetzt:

  • db_password wird zu my_secret_password_123
  • api_key wird zu api_key_abc123xyz

Hinweise

  • Die credentials.ini sollte nicht in Versionskontrolle (Git) eingecheckt werden
  • Platzhalter können nur durch Werte aus derselben Section ersetzt werden
  • Wenn ein Platzhalter nicht in der credentials.ini gefunden wird, bleibt er unverändert
  • Die Ersetzung erfolgt automatisch beim Laden der Konfiguration
  • Die Ersetzungslogik kann auch unabhängig genutzt werden über apply_credential_placeholders(...) oder apply_credential_placeholders_from_file(...)

API

Klasse: SimpleJobInit

  • SimpleJobInit(script_file_path: str)
    • Initialisiert Logging, lädt/prüft INI-Config, erzeugt Ordner (logs, tmp)
  • Eigenschaften
    • logger: konfigurierter logging.Logger
    • config: configparser.ConfigParser
  • Methoden
    • get_tmp_file_path(file_name: str) -> str: Pfad im tmp/-Verzeichnis
    • get_persistent_file_path(file_ending: str) -> str: Pfad <skriptname>.<file_ending>
    • get_job_script_version(include_git_tag: bool = False) -> str: ermittelt Skriptversion (Git/FS)
    • get_config_file_hash() -> str: SHA-256 Hash der INI-Datei
    • get_credentials_file_hash() -> str: SHA-256 Hash der Credentials-Datei (wirft ValueError wenn nicht vorhanden)
    • get_persistent_file_hash(file_ending: str) -> str: SHA-256 Hash einer beliebigen persistenten Datei
    • get_combined_hash(require_credentials: bool = True) -> str: kombinierter SHA-256 Hash aus Config und Credentials
    • get_config_file_version() -> str: cfg_<UTC-Zeit>_<sha256> basierend auf Datei-mtime und Hash
    • load_additional_config(extra_config_filepath: str, credentials_filepath: str | None = None) -> Dict[str, Set[str]]: Lädt eine zusätzliche INI in die Instanz-Config und führt Credential-Ersetzung aus (optional mit explizitem Credentials-Pfad)
    • log_config(secret_fields) -> None: loggt INI-Inhalt, maskiert definierte Felder (case-insensitive)
    • get_postgres_sqlalchemy_engine(db_config): baut SQLAlchemy-Engine aus INI-Werten

Top-Level-Funktion

  • get_script_version(script_file_path: str, include_git_tag: bool = False) -> str
    • Wie get_job_script_version, aber als freie Funktion für eigenständige Nutzung
  • apply_credential_placeholders(config, credentials, logger=None) -> Dict[str, Set[str]]
    • Ersetzt [[[[name]]]] Platzhalter in einer beliebig geladenen ConfigParser-Instanz
  • apply_credential_placeholders_from_file(config, credentials_filepath, logger=None) -> Dict[str, Set[str]]
    • Lädt Credentials aus Datei und ersetzt Platzhalter in einer beliebig geladenen ConfigParser-Instanz

Lizenz

MIT-Lizenz - siehe LICENSE für Details.

  • Project build with support of AI (Cursor IDE, Github Copilot).

Metadata

Release files for sji 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sji 0.5.0
File Size Uploaded Provenance Actions
sji-0.5.0.tar.gz 13.3 kB Without provenance Details for sji-0.5.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sji 0.5.0
File Interpreter ABI Platform Actions
sji-0.5.0-py3-none-any.whl Python 3 none any Details for sji-0.5.0-py3-none-any.whl

Total release size: 24.3 kB

Release files / sji-0.5.0.tar.gz

Download URL sji-0.5.0.tar.gz
Size 13.3 kB
Tags Source
SHA-256 checksum
How to use checksums
eb873b6486c07c551c7c12e51ab8249bcd44d5edb4ca1b278b82f84c3cdb2cd9
BLAKE2b-256 checksum
How to use checksums
a7fa7dbe7eb0040ae395a5d27b4359951d3705cc039647240f5de1f4d7f57a28
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.2

Release files / sji-0.5.0-py3-none-any.whl

Download URL sji-0.5.0-py3-none-any.whl
Size 11.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cb55459707af4377cff2fcd8b4251f955bb10770b23739a850da25aeed8def04
BLAKE2b-256 checksum
How to use checksums
b56101b8dd931233ea15c1a0dcdca2f46c4c5ac38140148fb76311214fb5ca9e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.2

Security for sji 0.5.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page