askrobots / dbbasic-object-primitive
Public
Python functions as REST objects, with clustering, load balancing and state replication; no containers or orchestration.
04_calculator.py · 3.8 KB · 164 lines
| 1 | """ |
| 2 | 04_calculator.py - Calculator with validation |
| 3 | """ |
| 4 | |
| 5 | _logger = None |
| 6 | _state_manager = None |
| 7 | |
| 8 | |
| 9 | def GET(request): |
| 10 | """ |
| 11 | Perform arithmetic operations. |
| 12 | |
| 13 | Request format: |
| 14 | { |
| 15 | 'a': <number>, |
| 16 | 'b': <number>, |
| 17 | 'operation': 'add' | 'subtract' | 'multiply' | 'divide' |
| 18 | } |
| 19 | """ |
| 20 | |
| 21 | # Validate input |
| 22 | validation_error = _validate_input(request) |
| 23 | if validation_error: |
| 24 | if _logger: |
| 25 | _logger.error( |
| 26 | 'Validation failed', |
| 27 | error=validation_error, |
| 28 | request=request, |
| 29 | ) |
| 30 | return {'status': 'error', 'message': validation_error} |
| 31 | |
| 32 | # Extract validated values |
| 33 | a = request['a'] |
| 34 | b = request['b'] |
| 35 | operation = request['operation'] |
| 36 | |
| 37 | # Perform calculation |
| 38 | try: |
| 39 | result = _calculate(a, b, operation) |
| 40 | |
| 41 | # Track usage |
| 42 | if _state_manager: |
| 43 | usage = _state_manager.get('usage_count', 0) |
| 44 | _state_manager.set('usage_count', usage + 1) |
| 45 | |
| 46 | # Log success |
| 47 | if _logger: |
| 48 | _logger.info( |
| 49 | 'Calculation performed', |
| 50 | a=a, |
| 51 | b=b, |
| 52 | operation=operation, |
| 53 | result=result, |
| 54 | ) |
| 55 | |
| 56 | return { |
| 57 | 'status': 'ok', |
| 58 | 'result': result, |
| 59 | 'operation': f'{a} {_get_symbol(operation)} {b} = {result}', |
| 60 | } |
| 61 | |
| 62 | except Exception as e: |
| 63 | # Log error |
| 64 | if _logger: |
| 65 | _logger.error( |
| 66 | 'Calculation failed', |
| 67 | error=str(e), |
| 68 | a=a, |
| 69 | b=b, |
| 70 | operation=operation, |
| 71 | ) |
| 72 | |
| 73 | return { |
| 74 | 'status': 'error', |
| 75 | 'message': str(e), |
| 76 | } |
| 77 | |
| 78 | |
| 79 | def POST(request): |
| 80 | """Get usage statistics""" |
| 81 | |
| 82 | if _state_manager: |
| 83 | usage_count = _state_manager.get('usage_count', 0) |
| 84 | else: |
| 85 | usage_count = 0 |
| 86 | |
| 87 | return { |
| 88 | 'status': 'ok', |
| 89 | 'usage_count': usage_count, |
| 90 | 'message': f'Calculator used {usage_count} times', |
| 91 | } |
| 92 | |
| 93 | |
| 94 | def _validate_input(request): |
| 95 | """Validate request input. Returns error message or None.""" |
| 96 | |
| 97 | # Check required fields |
| 98 | if 'a' not in request: |
| 99 | return 'Missing required field: a' |
| 100 | |
| 101 | if 'b' not in request: |
| 102 | return 'Missing required field: b' |
| 103 | |
| 104 | if 'operation' not in request: |
| 105 | return 'Missing required field: operation' |
| 106 | |
| 107 | # Validate types |
| 108 | try: |
| 109 | float(request['a']) |
| 110 | except (ValueError, TypeError): |
| 111 | return f"Field 'a' must be a number, got: {request['a']}" |
| 112 | |
| 113 | try: |
| 114 | float(request['b']) |
| 115 | except (ValueError, TypeError): |
| 116 | return f"Field 'b' must be a number, got: {request['b']}" |
| 117 | |
| 118 | # Validate operation |
| 119 | valid_operations = ['add', 'subtract', 'multiply', 'divide'] |
| 120 | if request['operation'] not in valid_operations: |
| 121 | return f"Invalid operation: {request['operation']}. Valid: {valid_operations}" |
| 122 | |
| 123 | # Division by zero check |
| 124 | if request['operation'] == 'divide' and float(request['b']) == 0: |
| 125 | return 'Cannot divide by zero' |
| 126 | |
| 127 | return None # All valid |
| 128 | |
| 129 | |
| 130 | def _calculate(a, b, operation): |
| 131 | """Perform the calculation""" |
| 132 | a = float(a) |
| 133 | b = float(b) |
| 134 | |
| 135 | if operation == 'add': |
| 136 | return a + b |
| 137 | elif operation == 'subtract': |
| 138 | return a - b |
| 139 | elif operation == 'multiply': |
| 140 | return a * b |
| 141 | elif operation == 'divide': |
| 142 | return a / b |
| 143 | else: |
| 144 | raise ValueError(f'Unknown operation: {operation}') |
| 145 | |
| 146 | |
| 147 | def _get_symbol(operation): |
| 148 | """Get math symbol for operation""" |
| 149 | symbols = { |
| 150 | 'add': '+', |
| 151 | 'subtract': '-', |
| 152 | 'multiply': '×', |
| 153 | 'divide': '÷', |
| 154 | } |
| 155 | return symbols.get(operation, '?') |
| 156 | |
| 157 | |
| 158 | __endpoint__ = { |
| 159 | 'name': 'calculator', |
| 160 | 'description': 'Arithmetic calculator with validation', |
| 161 | 'version': '1.0.0', |
| 162 | 'author': 'tutorial', |
| 163 | 'methods': ['GET', 'POST'], |
| 164 | } |