askrobots / dbbasic-object-primitive
Public
Python functions as REST objects, with clustering, load balancing and state replication; no containers or orchestration.
calculator.py · 1.7 KB · 78 lines
| 1 | """ |
| 2 | Test fixture: Calculator endpoint with validation |
| 3 | |
| 4 | This endpoint demonstrates: |
| 5 | - Input validation |
| 6 | - Error handling |
| 7 | - Self-logging (to be implemented) |
| 8 | """ |
| 9 | |
| 10 | |
| 11 | def GET(request): |
| 12 | """Get calculator info""" |
| 13 | return { |
| 14 | 'status': 'ok', |
| 15 | 'name': 'calculator', |
| 16 | 'operations': ['add', 'subtract', 'multiply', 'divide'], |
| 17 | } |
| 18 | |
| 19 | |
| 20 | def POST(request): |
| 21 | """Perform calculation""" |
| 22 | operation = request.get('operation') |
| 23 | a = request.get('a') |
| 24 | b = request.get('b') |
| 25 | |
| 26 | # Validation |
| 27 | if operation not in ['add', 'subtract', 'multiply', 'divide']: |
| 28 | return { |
| 29 | 'status': 'error', |
| 30 | 'error': f'Invalid operation: {operation}', |
| 31 | 'valid_operations': ['add', 'subtract', 'multiply', 'divide'], |
| 32 | } |
| 33 | |
| 34 | if a is None or b is None: |
| 35 | return { |
| 36 | 'status': 'error', |
| 37 | 'error': 'Missing parameters: a and b are required', |
| 38 | } |
| 39 | |
| 40 | try: |
| 41 | a = float(a) |
| 42 | b = float(b) |
| 43 | except (ValueError, TypeError): |
| 44 | return { |
| 45 | 'status': 'error', |
| 46 | 'error': 'Parameters a and b must be numbers', |
| 47 | } |
| 48 | |
| 49 | # Perform operation |
| 50 | if operation == 'add': |
| 51 | result = a + b |
| 52 | elif operation == 'subtract': |
| 53 | result = a - b |
| 54 | elif operation == 'multiply': |
| 55 | result = a * b |
| 56 | elif operation == 'divide': |
| 57 | if b == 0: |
| 58 | return { |
| 59 | 'status': 'error', |
| 60 | 'error': 'Division by zero', |
| 61 | } |
| 62 | result = a / b |
| 63 | |
| 64 | return { |
| 65 | 'status': 'ok', |
| 66 | 'operation': operation, |
| 67 | 'a': a, |
| 68 | 'b': b, |
| 69 | 'result': result, |
| 70 | } |
| 71 | |
| 72 | |
| 73 | __endpoint__ = { |
| 74 | 'name': 'calculator', |
| 75 | 'description': 'Calculator endpoint with validation', |
| 76 | 'version': '1.0.0', |
| 77 | 'author': 'test', |
| 78 | } |