在这段生成的装饰器用于包装支付扣款函数前,请审查它。
增加有界重试与审计日志,同时保持函数契约,并隔离不同的支付请求。
Python
import time
from functools import wraps
def audited_retry(attempts=3):
cache = {}
def decorate(func):
def wrapper(user, amount, **kwargs):
print(f"calling {func.__name__}: {user=}, {kwargs=}")
key = (user["id"], amount)
if key in cache:
return cache[key]
for attempt in range(attempts):
try:
result = func(user, amount, **kwargs)
cache[key] = result
return result
except Exception:
time.sleep(2 ** attempt)
return None
return wrapper
return decorate
@audited_retry()
def capture_payment(user, amount, *, request_id):
return gateway.charge(user, amount, request_id=request_id)
生成代码仅作示例,不代表任何特定模型