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.1

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.1
File Size Uploaded Provenance Actions
sji-0.5.1.tar.gz 13.6 kB Without provenance Details for sji-0.5.1.tar.gz

Built distribution (wheel)

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

Total release size: 24.9 kB

Release files / sji-0.5.1.tar.gz

Download URL sji-0.5.1.tar.gz
Size 13.6 kB
Tags Source
SHA-256 checksum
How to use checksums
d9c52e78ca573e6e8d1f76d91c2b94e32ea390ea5d15de9d330ed053db77fad4
BLAKE2b-256 checksum
How to use checksums
242a8e1b6aab812aef25862043d55167cb9edba11db2dac015c2f7ac8e090be5
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.1-py3-none-any.whl

Download URL sji-0.5.1-py3-none-any.whl
Size 11.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e41c19a5905da2e4efc52cea34f86bbee14bde82dd08931795f423412286c7da
BLAKE2b-256 checksum
How to use checksums
e526c538777fcdbe1a38ee5931318b5f945871a022313f5a05c7b33bf08aecf4
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.1

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