imednet.utils package
Submodules
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.filters.filter_by_attribute(items, attr_name, target_value)[source]
Filter a list of objects by a specific attribute value using strict string comparison.
This function handles the common case where API IDs might be returned as integers or strings, ensuring consistent comparison by converting both to strings.
- Parameters:
items (
List[TypeVar(T)]) – List of objects to filter.attr_name (
str) – The name of the attribute to check on each object.target_value (
Any) – The value to filter for.
- Return type:
List[TypeVar(T)]- Returns:
A new list containing only the items where the attribute matches the target value.
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.typing module
Type definitions for imednet SDK utilities.
imednet.utils.json_logging module
Example
>>> from imednet.utils.json_logging import configure_json_logging
>>> configure_json_logging()
>>> import logging
>>> logging.getLogger(__name__).warning("hi")
{"message": "hi", "level": "warning", ...}
imednet.utils.url module
Example
>>> from imednet.utils.url import sanitize_base_url
>>> sanitize_base_url("https://example.com/api/")
'https://example.com'
imednet.utils.validators module
- imednet.utils.validators.parse_bool(v)[source]
Normalize boolean values from various representations. Accepts bool, str, int, float and returns a bool.
- Return type:
bool- Parameters:
v (Any) –
- 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) –
Examples
>>> from imednet.utils.validators import (
... parse_bool,
... parse_datetime,
... parse_int_or_default,
... parse_str_or_default,
... parse_list_or_default,
... parse_dict_or_default,
... )
>>> parse_bool("true")
True
>>> parse_datetime("2020-01-02T03:04:05Z").year
2020
>>> parse_int_or_default("bad", default=2)
2
>>> parse_str_or_default(123)
'123'
>>> parse_list_or_default("a")
['a']
>>> parse_dict_or_default(None)
{}
Module contents
Re-exports utility functions for easier access.
- 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.