imednet.utils package

Re-exports utility functions for easier access.

class imednet.utils.DataFrame

Bases: object

imednet.utils.build_filter_string(filters, and_connector=';', or_connector=',')[source]

Return a filter string constructed according to iMednet rules.

Each key in filters is converted to camelCase. Raw values imply equality, tuples allow explicit operators, and lists generate multiple equality filters joined by or_connector. Conditions are then joined by and_connector.

Return type:

str

Parameters:
  • filters (Dict[str, Any | Tuple[str, Any] | List[Any]]) –

  • and_connector (str) –

  • or_connector (str) –

Examples

>>> build_filter_string({'age': ('>', 30), 'status': 'active'})
'age>30;status==active'
>>> build_filter_string({'type': ['A', 'B']})
'type==A,type==B'
imednet.utils.configure_json_logging(level=20)[source]

Configure root logger to emit JSON formatted logs.

Return type:

None

Parameters:

level (int) –

imednet.utils.format_iso_datetime(dt)[source]

Format a datetime object into an ISO 8601 string ending with ‘Z’.

Parameters:

dt (datetime) – datetime object (naive or timezone-aware).

Return type:

str

Returns:

A string representing the datetime in ISO 8601 format.

imednet.utils.parse_iso_datetime(date_str)[source]

Parse an ISO 8601 date/time string into a datetime object.

Handles timestamps ending with ‘Z’ as UTC.

Parameters:

date_str (str) – ISO 8601 formatted date/time string.

Return type:

datetime

Returns:

A timezone-aware datetime object.

Raises:

ValueError – If the input string is not a valid ISO format.

imednet.utils.sanitize_base_url(url)[source]

Return base URL without trailing slashes or /api suffix.

Return type:

str

Parameters:

url (str) –

imednet.utils.sanitize_csv_formula(value)[source]

Sanitize a value to prevent CSV/Excel Formula Injection.

Prefixes strings starting with =, +, -, or @ (even after whitespace) with a single quote. Lists and tuples are recursively sanitized.

Return type:

Any

Parameters:

value (Any) –

imednet.utils.validate_partition_key(key)[source]

Reject partition keys that could escape or reshape the target directory.

Return type:

None

Parameters:

key (str) –

Submodules

imednet.utils.arrow module

PyArrow serialization helpers.

imednet.utils.arrow.to_arrow_table(data_records, schema=None)[source]

Serialize record dictionaries (or Pydantic-like objects) into a pyarrow.Table.

Parameters:
  • data_records – Record payloads to serialize. Each item must be a dictionary or expose a model_dump() method that returns a dictionary.

  • schema – Optional explicit Arrow schema. When provided, output columns follow schema order and types; when omitted, columns and types are inferred. Naive datetime values are interpreted as UTC. When schema inference is used, datetime columns use microsecond precision. Boolean strings accept true/false, 1/0, yes/no, y/n, and t/f.

Returns:

A fully initialized pyarrow.Table with deterministic columns and null values for missing or empty-string inputs.

Raises:
  • ImportError – If pyarrow is not installed.

  • TypeError – If a record is not dict-like and does not expose model_dump.

Return type:

pa.Table

imednet.utils.dates module

Utility functions for parsing and formatting ISO date/time strings.

imednet.utils.dates.format_iso_datetime(dt)[source]

Format a datetime object into an ISO 8601 string ending with ‘Z’.

Parameters:

dt (datetime) – datetime object (naive or timezone-aware).

Return type:

str

Returns:

A string representing the datetime in ISO 8601 format.

imednet.utils.dates.parse_iso_datetime(date_str)[source]

Parse an ISO 8601 date/time string into a datetime object.

Handles timestamps ending with ‘Z’ as UTC.

Parameters:

date_str (str) – ISO 8601 formatted date/time string.

Return type:

datetime

Returns:

A timezone-aware datetime object.

Raises:

ValueError – If the input string is not a valid ISO format.

imednet.utils.filters module

Utility functions for building API filter strings.

This module provides functionality to construct filter query parameters for iMednet API endpoints based on the reference documentation.

imednet.utils.filters.build_filter_string(filters, and_connector=';', or_connector=',')[source]

Return a filter string constructed according to iMednet rules.

Each key in filters is converted to camelCase. Raw values imply equality, tuples allow explicit operators, and lists generate multiple equality filters joined by or_connector. Conditions are then joined by and_connector.

Return type:

str

Parameters:
  • filters (Dict[str, Any | Tuple[str, Any] | List[Any]]) –

  • and_connector (str) –

  • or_connector (str) –

Examples

>>> build_filter_string({'age': ('>', 30), 'status': 'active'})
'age>30;status==active'
>>> build_filter_string({'type': ['A', 'B']})
'type==A,type==B'

imednet.utils.json_logging module

imednet.utils.json_logging.configure_json_logging(level=20)[source]

Configure root logger to emit JSON formatted logs.

Return type:

None

Parameters:

level (int) –

imednet.utils.pandas module

Pandas helpers for working with iMednet models.

imednet.utils.pandas.export_records_csv(sdk, study_key, file_path, *, flatten=True)[source]

Fetch all records for study_key and write them to file_path.

Parameters are passed to records_to_dataframe() and the resulting DataFrame is written with pandas.DataFrame.to_csv() using index=False.

Return type:

None

Parameters:
  • sdk (ImednetSDK) –

  • study_key (str) –

  • file_path (str) –

  • flatten (bool) –

imednet.utils.pandas.records_to_dataframe(records, *, flatten=False)[source]

Convert a list of Record to a DataFrame.

Each record is converted using pydantic.BaseModel.model_dump() with by_alias=False. If flatten is True the record_data column is expanded using pandas.json_normalize() so that each variable becomes a column in the resulting DataFrame.

Return type:

DataFrame

Parameters:
  • records (List[Record]) –

  • flatten (bool) –

imednet.utils.security module

Security utilities.

imednet.utils.security.sanitize_csv_formula(value)[source]

Sanitize a value to prevent CSV/Excel Formula Injection.

Prefixes strings starting with =, +, -, or @ (even after whitespace) with a single quote. Lists and tuples are recursively sanitized.

Return type:

Any

Parameters:

value (Any) –

imednet.utils.security.validate_header_value(value)[source]

Validate that a header value does not contain newline characters.

Parameters:

value (str) – The header value to validate.

Raises:

ClientError – If the value contains newline characters.

Return type:

None

imednet.utils.security.validate_partition_key(key)[source]

Reject partition keys that could escape or reshape the target directory.

Return type:

None

Parameters:

key (str) –

imednet.utils.typing module

Type definitions for imednet SDK utilities.

class imednet.utils.typing.DataFrame

Bases: object

imednet.utils.typing.FilterScalar

A single filter value accepted by endpoint list and convenience methods.

Supported forms:

  • A scalar str, int, float, or bool – implies equality.

  • A two-element tuple (operator, scalar) – e.g. (">", 30).

  • A list of scalars – generates OR-joined equality filters.

alias of Optional[Union[str, int, float, bool]]

imednet.utils.typing.ItemId

Accepted types for an endpoint item-ID parameter (path segment or filter value).

alias of Union[str, int]

imednet.utils.typing.JsonDict

Generic JSON object type (mapping of string keys to arbitrary values).

alias of Dict[str, Any]

imednet.utils.url module

imednet.utils.url.build_safe_path(base_path, *segments)[source]

Build a normalized relative path using HTTPX URL joining.

Parameters:
  • base_path (str) – Base path segment to start from.

  • *segments (Any) – Additional path segments. Non-string values are stringified.

Return type:

str

Returns:

A slash-normalized relative path with URL-encoded segments decoded (for example, "a%2Fb" becomes "a/b").

imednet.utils.url.redact_url_query(url, sensitive_params=None)[source]

Return URL with sensitive query parameters redacted.

Return type:

str

Parameters:
  • url (str) –

  • sensitive_params (Set[str] | None) –

imednet.utils.url.sanitize_base_url(url)[source]

Return base URL without trailing slashes or /api suffix.

Return type:

str

Parameters:

url (str) –

imednet.utils.validators module

imednet.utils.validators.is_boolean_token(value)[source]
Return type:

bool

Parameters:

value (str) –

imednet.utils.validators.is_missing_value(value)[source]
Return type:

bool

Parameters:

value (Any) –

imednet.utils.validators.parse_bool(v)[source]

Normalize boolean values from various representations. Accepts bool, str, int, float and returns a bool.

Defaults to False for unknown or unparseable types (e.g. None, [], object()). String representations like ‘1.0’, ‘inf’, and ‘nan’ are treated as truthy via float fallback.

Return type:

bool

Parameters:

v (Any) –

Example

>>> parse_bool("yes")
True
>>> parse_bool("1.0")
True
>>> parse_bool(None)
False
imednet.utils.validators.parse_datetime(v)[source]

Parse an ISO datetime string, numeric timestamp, or return a sentinel value.

The SDK historically returns datetime(1969, 4, 20, 16, 20) when a timestamp field is empty. This helper mirrors that behaviour for backward compatibility.

Parameters:

v (str | int | float | datetime) – Date string, numeric timestamp (seconds since epoch), or datetime object. Numeric values are assumed to be UTC timestamps.

Return type:

datetime

imednet.utils.validators.parse_dict_or_default(v, default_factory=<class 'dict'>)[source]

Normalize dictionary values, defaulting if None. Ensures result is a dict.

Return type:

Dict[str, Any]

Parameters:
  • v (Any) –

  • default_factory (Callable[[], Dict[str, Any]]) –

imednet.utils.validators.parse_int_or_default(v, default=0, strict=False)[source]

Normalize integer values, defaulting if None or empty string. If strict=True, raise ValueError on parse failure.

Return type:

int

Parameters:
  • v (Any) –

  • default (int) –

  • strict (bool) –

imednet.utils.validators.parse_list_or_default(v, default_factory=<class 'list'>)[source]

Normalize list values, defaulting if None. Ensures result is a list.

Return type:

List[TypeVar(T)]

Parameters:
  • v (Any) –

  • default_factory (Callable[[], List[T]]) –

imednet.utils.validators.parse_str_or_default(v, default='')[source]

Normalize string values, defaulting if None.

Return type:

str

Parameters:
  • v (Any) –

  • default (str) –