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
filtersis converted to camelCase. Raw values imply equality, tuples allow explicit operators, and lists generate multiple equality filters joined byor_connector. Conditions are then joined byand_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
/apisuffix.- 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
datetimevalues are interpreted as UTC. When schema inference is used, datetime columns use microsecond precision. Boolean strings accepttrue/false,1/0,yes/no,y/n, andt/f.
- Returns:
A fully initialized
pyarrow.Tablewith deterministic columns and null values for missing or empty-string inputs.- Raises:
ImportError – If
pyarrowis 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
filtersis converted to camelCase. Raw values imply equality, tuples allow explicit operators, and lists generate multiple equality filters joined byor_connector. Conditions are then joined byand_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.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_keyand write them tofile_path.Parameters are passed to
records_to_dataframe()and the resulting DataFrame is written withpandas.DataFrame.to_csv()usingindex=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
Recordto a DataFrame.Each record is converted using
pydantic.BaseModel.model_dump()withby_alias=False. IfflattenisTruetherecord_datacolumn is expanded usingpandas.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.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
listand convenience methods.Supported forms:
A scalar
str,int,float, orbool– implies equality.A two-element tuple
(operator, scalar)– e.g.(">", 30).A
listof scalars – generatesOR-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.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) –