JustCaptain kod-buduschego
llm/middle-8396c3
Перейти к файлу
Код
kod-buduschego Python 2025-20264.4. Декораторpracticesskilloktask_7.py
anc update c70a58f 8 октября 2026 г.
task_7.py
"""
TASK-S1 — Аудит финансовых операций
Контекст
Все операции списания средств должны попадать в аудит.
Декоратор должен сохранять: - время вызова - аргументы - результат - исключения
в общий список:
audit_logs = []

⸻

Формат записи

{
"timestamp": "...",
"function": "withdraw",
"args": (...),
"result": ...
}

"""

from datetime import datetime

accounts: dict[str, int] = {"A100": 5000, "A101": 12000}
audit_logs: list = []


def logs(func):
    def wrapper(*args, **kwargs):
        global audit_logs
        timestamp = datetime.now()
        function = func.__name__
        try:
            result = func(*args, **kwargs)
            info = {
                "timestamp": timestamp,
                "function": function,
                "args": (args, kwargs),
                "result": result,
            }
            audit_logs.append(info)
            return result
        except:
            result = "ERROR"
            info = {
                "timestamp": timestamp,
                "function": function,
                "args": (args, kwargs),
                "result": result,
            }
            audit_logs.append(info)
            return None

    return wrapper


@logs
def withdraw(account_id: str, amount: int) -> int:
    global accounts
    accounts[account_id] = accounts[account_id] - amount
    return accounts[account_id]


withdraw("A100", 400)
withdraw("A101", 300)
print(audit_logs)