Smarter Helper Mixin
- class smarter.common.mixins.SmarterHelperMixin(*args, **kwargs)[source]
Bases:
objectA generic mixin providing helper functions for Smarter classes.
This mixin offers utility methods and properties commonly needed across Smarter classes, such as:
Standardized class name formatting for logging and display
URL amnesty lists for exempting certain endpoints from checks
JSON and YAML serialization/deserialization utilities
Data conversion and dictionary utilities
Secure string masking for logging sensitive information
Environment variable parsing helpers
Fernet encryption key generation
File handling utilities for CSV and YAML files
Case conversion utilities (snake_case, camelCase, PascalCase, RFC 1034)
- Intended Usage:
Inherit this mixin in Smarter classes to gain access to a suite of common helper methods and properties, reducing code duplication and standardizing utility logic.
Examples:
class MyClass(SmarterHelperMixin): pass obj = MyClass() print(obj.formatted_class_name) print(obj.data_to_dict('{"foo": "bar"}')) print(obj.mask_string("my-secret-key"))
Main Features:
formatted_class_name: Returns the class name formatted for logging.amnesty_urls: List of URL paths exempt from certain checks.deserves_amnesty(slug): Checks if a URL deserves amnesty.smarter_build_absolute_uri(request): Safely builds an absolute URI from a Django HttpRequest.mask_string(...): Masks sensitive strings for secure logging.bool_environment_variable(var_name, default): Parses environment variables as booleans.generate_fernet_encryption_key(): Generates a Fernet encryption key.data_to_dict(data): Converts JSON/YAML string or dict to dict.sorted_dict(data): Returns a sorted copy of a dictionary.dict_is_contained_in(dict1, dict2): Checks if one dict is contained in another.dict_is_subset(small, big): Checks if one dict is a subset of another.recursive_sort_dict(data): Recursively sorts a dictionary.get_readonly_csv_file(file_path): Opens a CSV file in read-only mode.get_readonly_yaml_file(file_path): Opens a YAML file in read-only mode.Case conversion utilities:
to_snake_case,to_snake_case,to_snake_case,snake_case,to_camel_case,to_snake_case,rfc1034_compliant_str,rfc1034_compliant_to_snake.
- __init__(*args, **kwargs)[source]
Note: this needs to exist.
something in the Python MRO requires it, even if it does nothing. If you remove this, you will get a mysterious error about something downstream expecting exactly one object.
- property amnesty_urls: list[str][source]
Returns a list of URLs that are exempt from certain checks.
- bool_environment_variable(var_name, default=False)[source]
Retrieves a boolean value from an environment variable.
This method checks the specified environment variable and returns its value as a boolean. It recognizes common truthy values such as “true”, “1”, “yes”, and “on”. If the variable is not set or cannot be interpreted as a boolean, it returns the provided default value.
- data_to_dict(data)[source]
Converts data to a dictionary, handling different types of input.
This method accepts either a dictionary or a string. If a string is provided, it will attempt to parse it as JSON first, and if that fails, as YAML. If parsing fails or the data type is unsupported, a SmarterValueError is raised.
- deserves_amnesty(slug)[source]
Determines if a given URL deserves amnesty based on the amnesty URLs list.
This excuses certain endpoints (like health checks) from select middleware checks.
- dict_is_contained_in(dict1, dict2)[source]
Checks if one dictionary is contained within another.
This method determines if all key-value pairs in dict1 are present in dict2.
- dict_is_subset(small, big)[source]
Checks if one dictionary is a subset of another.
This method determines if all key-value pairs in the small dictionary are present in the big dictionary. It returns True if the small dictionary is a subset of the big dictionary, and False otherwise.
- property formatted_class_name: str[source]
Returns the class name formatted for logging.
- Returns:
The formatted class name as a string.
- Return type:
- formatted_json(json_obj)[source]
Formats a JSON object as a pretty-printed string with ANSI color codes for logging.
- property formatted_state_not_ready: str[source]
Returns the not-ready state formatted for logging.
- Returns:
The formatted not-ready state as a string.
- Return type:
- property formatted_state_ready: str[source]
Returns the readiness state formatted for logging.
- Returns:
The formatted readiness state as a string.
- Return type:
- formatted_text(text, color_code='\\x1b[1;31m')[source]
Formats text with ANSI color codes for logging.
- generate_fernet_encryption_key()[source]
Generates a Fernet encryption key.
This method creates a new Fernet encryption key, which can be used for secure encryption and decryption of data. The generated key is returned as a URL-safe base64-encoded string.
- Returns:
A new Fernet encryption key.
- Return type:
- get_readonly_csv_file(file_path)[source]
Retrieves a read-only file object for a CSV file.
This method opens the specified CSV file in read-only mode and returns a file object that can be used to read its contents. It ensures that the file is not modified during the reading process.
- Parameters:
file_path (
str) – The path to the CSV file to open.- Returns:
A read-only file object for the specified CSV file.
- Return type:
file
- get_readonly_yaml_file(file_path)[source]
Retrieves a read-only file object for a YAML file.
This method opens the specified YAML file in read-only mode and returns a file object that can be used to read its contents. It ensures that the file is not modified during the reading process.
- Parameters:
file_path (
str) – The path to the YAML file to open.- Returns:
A read-only file object for the specified YAML file.
- Return type:
file
- property health_check_urls: list[str][source]
Returns a list of URL paths that are considered health check endpoints.
- mask_string(string='', mask_char='*', mask_length=4, string_length=8)[source]
Masks a string for secure logging.
This utility function masks all but the last unmasked_chars characters of the input string, replacing them with asterisks. It is useful for logging sensitive information like API keys or passwords.
- property ready: bool
Indicates whether the object is ready for use.
This is a placeholder that should be overridden in subclasses.
- Returns:
True if ready, False otherwise.
- Return type:
- recursive_sort_dict(data)[source]
Recursively sorts a dictionary by its keys.
This method takes a dictionary and returns a new dictionary with all keys sorted in ascending order. If any values are also dictionaries, they will be sorted recursively as well.
- rfc1034_compliant_str(name)[source]
Converts a string to an RFC 1034 compliant format.
This method takes a string and converts it to a format that complies with RFC 1034, which is commonly used for domain names. It replaces invalid characters with hyphens and ensures the resulting string is lowercase.
- rfc1034_compliant_to_snake(name)[source]
Converts an RFC 1034 compliant string to snake_case.
This method takes a string in RFC 1034 compliant format and converts it to snake_case. It replaces hyphens with underscores and ensures the resulting string is lowercase.
- smarter_build_absolute_uri(request)[source]
Attempts to get the absolute URI from a request object.
This utility function tries to retrieve the request URL from any valid child class of
django.http.HttpRequest. It is especially useful in unit tests or scenarios where the request object may not implementbuild_absolute_uri().- Parameters:
request (
HttpRequest) – The request object.- Returns:
The absolute request URL.
- Return type:
- Raises:
SmarterValueError – If the URI cannot be built from the request.
- to_camel_case(data, convert_values=False)[source]
Converts a snake_case string to camelCase.
This method takes a string in snake_case format and converts it to camelCase. It is useful for standardizing naming conventions across different formats.