askrobots / dbbasic-object-primitive
Public
Python functions as REST objects, with clustering, load balancing and state replication; no containers or orchestration.
03_counter.py · 1.3 KB · 66 lines
| 1 | """ |
| 2 | 03_counter.py - Stateful counter |
| 3 | """ |
| 4 | |
| 5 | _logger = None |
| 6 | _state_manager = None |
| 7 | |
| 8 | |
| 9 | def GET(request): |
| 10 | """Increment counter and return current value""" |
| 11 | |
| 12 | # Get current count from persistent state |
| 13 | if _state_manager: |
| 14 | count = _state_manager.get('count', 0) |
| 15 | count += 1 |
| 16 | _state_manager.set('count', count) |
| 17 | else: |
| 18 | count = 1 |
| 19 | |
| 20 | # Log the increment |
| 21 | if _logger: |
| 22 | _logger.info( |
| 23 | 'Counter incremented', |
| 24 | count=count, |
| 25 | user_id=request.get('user_id'), |
| 26 | ) |
| 27 | |
| 28 | return { |
| 29 | 'status': 'ok', |
| 30 | 'count': count, |
| 31 | 'message': f'Counter is now at {count}', |
| 32 | } |
| 33 | |
| 34 | |
| 35 | def POST(request): |
| 36 | """Reset counter to 0""" |
| 37 | |
| 38 | # Get old value |
| 39 | if _state_manager: |
| 40 | old_value = _state_manager.get('count', 0) |
| 41 | _state_manager.set('count', 0) |
| 42 | else: |
| 43 | old_value = 0 |
| 44 | |
| 45 | # Log the reset |
| 46 | if _logger: |
| 47 | _logger.warning( |
| 48 | 'Counter reset', |
| 49 | old_value=old_value, |
| 50 | user_id=request.get('user_id'), |
| 51 | ) |
| 52 | |
| 53 | return { |
| 54 | 'status': 'ok', |
| 55 | 'count': 0, |
| 56 | 'message': f'Counter reset from {old_value} to 0', |
| 57 | } |
| 58 | |
| 59 | |
| 60 | # Metadata |
| 61 | __endpoint__ = { |
| 62 | 'name': 'counter', |
| 63 | 'description': 'A simple counter that increments on GET, resets on POST', |
| 64 | 'version': '1.0.0', |
| 65 | 'author': 'tutorial', |
| 66 | } |