init.py


Overview

This init.py file serves as a foundational utility module within the InfiniFlow project, providing a broad suite of helper functions, classes, and configuration management utilities used across the codebase. Its main responsibilities include:

This module acts as a core utility toolkit that other parts of the system depend on to perform common low-level tasks, facilitating cleaner, safer, and more consistent code.


Detailed Explanations

Global Constants and Variables


Functions

conf_realpath(conf_name: str) -> str

Returns the absolute path of a configuration file inside the conf/ directory relative to the project base directory.

Usage:

config_path = conf_realpath("service.yaml")

read_config(conf_name: str = SERVICE_CONF) -> dict

Loads and merges global and local YAML configuration files.

Exceptions:

Example:

configs = read_config()

show_configs() -> None

Logs the current configuration with sensitive values masked (e.g., passwords replaced with ********).


get_base_config(key: str, default=None) -> any

Retrieves a configuration value by key from the merged CONFIGS dictionary.


string_to_bytes(string: str|bytes) -> bytes

Ensures the input string is returned as bytes using UTF-8 encoding if input is str.


bytes_to_string(byte: bytes) -> str

Decodes bytes to UTF-8 string.


json_dumps(src: any, byte: bool = False, indent: int | None = None, with_type: bool = False) -> str | bytes

Serializes a Python object to JSON string or bytes.


json_loads(src: str | bytes, object_hook=None, object_pairs_hook=None) -> any

Deserializes JSON string or bytes to Python object.


current_timestamp() -> int

Returns the current timestamp in milliseconds since the Unix epoch.


timestamp_to_date(timestamp: int | float, format_string: str = "%Y-%m-%d %H:%M:%S") -> str

Converts a millisecond timestamp to a formatted date string.


date_string_to_timestamp(time_str: str, format_string: str = "%Y-%m-%d %H:%M:%S") -> int

Converts a formatted date string to a millisecond timestamp.


serialize_b64(src: any, to_str: bool = False) -> bytes | str

Serializes a Python object using pickle, then base64 encodes it.


deserialize_b64(src: str | bytes) -> any

Decodes base64 string/bytes and deserializes using pickle.


get_lan_ip() -> str

Retrieves the local LAN IP address.


from_dict_hook(in_dict: dict) -> any

Custom JSON object hook for deserialization.


decrypt_database_password(password: str) -> str

Decrypts a database password if encryption is enabled in config.


decrypt_database_config(database: dict = None, passwd_key: str = "password", name: str = "database") -> dict

Decrypts the password in a database config dictionary.


update_config(key: str, value: any, conf_name: str = SERVICE_CONF) -> None

Updates a key-value pair in the main configuration file.


get_uuid() -> str

Returns a new UUID string (UUID1 hex format).


datetime_format(date_time: datetime.datetime) -> datetime.datetime

Returns a datetime object truncated to seconds precision (dropping microseconds).


get_format_time() -> datetime.datetime

Returns the current datetime truncated to seconds.


str2date(date_time: str) -> datetime.datetime

Parses a string in the format %Y-%m-%d into a datetime.datetime object.


elapsed2time(elapsed: int | float) -> str

Converts elapsed milliseconds into a string formatted as HH:MM:SS.


decrypt(line: str) -> str

Decrypts an RSA encrypted base64-encoded string using a private key stored in conf/private.pem.


decrypt2(crypt_text: str) -> str

Alternative RSA decryption method for base64 encoded input, addressing specific decode length edge cases.


download_img(url: str) -> str

Downloads an image from a URL and returns a base64-encoded data URI string.


delta_seconds(date_string: str) -> float

Returns the number of seconds elapsed between the given date string ("%Y-%m-%d %H:%M:%S") and now.


hash_str2int(line: str, mod: int = 10**8) -> int

Hashes a string using SHA1, converts to integer, and returns modulo mod (default 100 million).


Classes

BaseType

Base class designed to be inherited by other classes for serialization support.


CustomJSONEncoder(json.JSONEncoder)

A JSON encoder subclass that extends support for additional Python types.


RestrictedUnpickler(pickle.Unpickler)

A pickle unpickler subclass that restricts unpickling to a predefined whitelist of safe modules.


Important Implementation Details


Interactions with Other Parts of the System


Usage Examples

from utils import conf_realpath, show_configs, get_base_config, json_dumps, deserialize_b64

# Load and show current config with sensitive data masked
show_configs()

# Get specific config value
db_host = get_base_config('database')['host']

# Serialize an object to JSON with type info
json_data = json_dumps(my_obj, with_type=True)

# Deserialize safely from base64 pickle string
obj = deserialize_b64(pickled_str)

# Get current timestamp in ms
now_ms = current_timestamp()

# Convert timestamp to human-readable string
date_str = timestamp_to_date(now_ms)

# Decrypt database password from config
db_config = decrypt_database_config()

# Update config key safely
update_config('new_key', 'new_value')

Mermaid Diagram - Class Structure

classDiagram
    class BaseType {
        +to_dict() dict
        +to_dict_with_type() dict
    }

    class CustomJSONEncoder {
        +__init__(with_type=False)
        +default(obj)
    }

    class RestrictedUnpickler {
        +find_class(module, name)
    }

    BaseType <|-- CustomJSONEncoder
    RestrictedUnpickler --|> pickle.Unpickler

Summary

This init.py module is a comprehensive utility foundation for the InfiniFlow project. It centralizes configuration management, secure serialization/deserialization, cryptographic helpers, and various utility functions that are widely reused. Its design emphasizes security (e.g., restricted unpickling, encrypted password handling), flexibility (config layering, environment overrides), and extensibility (custom JSON encoding). Understanding this file is key for developers working on configuration, data interchange, and security-sensitive operations within the system.