|
| 1 | +# decorators.py |
| 2 | + |
| 3 | +import time |
| 4 | +import logging |
| 5 | +from functools import wraps |
| 6 | + |
| 7 | +# Configure logging |
| 8 | +logging.basicConfig(level=logging.INFO) |
| 9 | + |
| 10 | +def log_function_call(func): |
| 11 | + @wraps(func) |
| 12 | + def wrapper(*args, **kwargs): |
| 13 | + logging.info(f"Calling function '{func.__name__}' with arguments {args} and keyword arguments {kwargs}") |
| 14 | + result = func(*args, **kwargs) |
| 15 | + logging.info(f"Function '{func.__name__}' returned {result}") |
| 16 | + return result |
| 17 | + return wrapper |
| 18 | + |
| 19 | +def timing_decorator(func): |
| 20 | + @wraps(func) |
| 21 | + def wrapper(*args, **kwargs): |
| 22 | + start_time = time.time() |
| 23 | + result = func(*args, **kwargs) |
| 24 | + end_time = time.time() |
| 25 | + execution_time = end_time - start_time |
| 26 | + print(f"Function '{func.__name__}' took {execution_time:.4f} seconds to execute") |
| 27 | + return result |
| 28 | + return wrapper |
| 29 | + |
| 30 | +def requires_authentication(func): |
| 31 | + @wraps(func) |
| 32 | + def wrapper(user, *args, **kwargs): |
| 33 | + if not user.get('authenticated'): |
| 34 | + return "Access Denied: User not authenticated" |
| 35 | + return func(user, *args, **kwargs) |
| 36 | + return wrapper |
| 37 | + |
| 38 | +def cache_results(func): |
| 39 | + cache = {} |
| 40 | + @wraps(func) |
| 41 | + def wrapper(*args, **kwargs): |
| 42 | + if args in cache: |
| 43 | + return cache[args] |
| 44 | + result = func(*args, **kwargs) |
| 45 | + cache[args] = result |
| 46 | + return result |
| 47 | + return wrapper |
| 48 | + |
| 49 | +def rate_limit(max_calls, period): |
| 50 | + def decorator(func): |
| 51 | + last_called = [0] |
| 52 | + @wraps(func) |
| 53 | + def wrapper(*args, **kwargs): |
| 54 | + current_time = time.time() |
| 55 | + if current_time - last_called[0] < period: |
| 56 | + return "Rate limit exceeded. Please try again later." |
| 57 | + last_called[0] = current_time |
| 58 | + return func(*args, **kwargs) |
| 59 | + return wrapper |
| 60 | + return decorator |
0 commit comments