Утилиты¶
Вспомогательные функции для работы с API.
- aioyookassa.core.utils.generate_idempotence_key() str[source]¶
Generate a unique idempotence key for requests.
- Returns:
UUID string.
- Return type:
str
- Seealso:
- aioyookassa.core.utils.create_idempotence_headers() Dict[str, str][source]¶
Create headers with idempotence key for requests.
- Returns:
Headers dictionary with Idempotence-Key.
- Return type:
Dict[str, str]
- aioyookassa.core.utils.normalize_params(params: BaseModel | dict | None, params_class: Type[BaseModel] | None = None) dict[source]¶
Normalize params to dictionary.
- Parameters:
params – Parameters as Pydantic model, dict, or None.
params_class – Optional Pydantic model class for validation.
- Returns:
Dictionary of parameters.
- aioyookassa.core.utils.format_datetime_to_iso(dt: Any) str | None[source]¶
Format datetime object to ISO string.
- Parameters:
dt – Datetime object or None.
- Returns:
ISO formatted string or None.
- aioyookassa.core.utils.format_datetime_params(params: Dict[str, Any], datetime_fields: List[str]) Dict[str, Any][source]¶
Format datetime fields in params dictionary to ISO strings.
- Parameters:
params – Parameters dictionary.
datetime_fields – List of field names to format.
- Returns:
Dictionary with formatted datetime fields.
- aioyookassa.core.utils.remove_none_values(data: Dict[str, Any]) Dict[str, Any][source]¶
Remove None values from dictionary.
This utility function removes all keys with None values from a dictionary, which is commonly needed when building API request parameters.
- Parameters:
data – Dictionary to clean.
- Returns:
Dictionary without None values.
- Example:
>>> remove_none_values({"a": 1, "b": None, "c": "value"}) {"a": 1, "c": "value"}
Примеры использования¶
Генерация ключа идемпотентности¶
from aioyookassa.core.utils import generate_idempotence_key, create_idempotence_headers
# Генерация ключа
key = generate_idempotence_key()
print(key) # "550e8400-e29b-41d4-a716-446655440000"
# Создание заголовков
headers = create_idempotence_headers()
# {"Idempotence-Key": "550e8400-e29b-41d4-a716-446655440000"}
Удаление None значений¶
from aioyookassa.core.utils import remove_none_values
# Удаление None значений из словаря
params = {
"amount": 100.0,
"description": "Test payment",
"metadata": None,
"receipt": None,
}
cleaned = remove_none_values(params)
# {"amount": 100.0, "description": "Test payment"}
Нормализация параметров¶
from aioyookassa.core.utils import normalize_params
from aioyookassa.types.params import CreatePaymentParams
# Нормализация из Pydantic модели
params = CreatePaymentParams(amount=PaymentAmount(...), description="Test")
normalized = normalize_params(params)
# {"amount": {...}, "description": "Test"}
# Нормализация из словаря
params_dict = {"amount": {...}, "description": "Test"}
normalized = normalize_params(params_dict, CreatePaymentParams)
# Валидированный и нормализованный словарь
Форматирование дат¶
from datetime import datetime
from aioyookassa.core.utils import format_datetime_to_iso, format_datetime_params
# Форматирование одной даты
dt = datetime(2024, 1, 1, 12, 0, 0)
iso_string = format_datetime_to_iso(dt)
# "2024-01-01T12:00:00"
# Форматирование нескольких полей
params = {
"created_at": datetime(2024, 1, 1),
"expires_at": datetime(2024, 12, 31),
"other_field": "value",
}
formatted = format_datetime_params(
params, ["created_at", "expires_at"]
)
# {"created_at": "2024-01-01T00:00:00", "expires_at": "2024-12-31T00:00:00", "other_field": "value"}