askrobots / dbbasic-object-primitive
Public
Python functions as REST objects, with clustering, load balancing and state replication; no containers or orchestration.
blog.py · 12.1 KB · 404 lines
| 1 | """ |
| 2 | Blog System - Object Primitive Style |
| 3 | |
| 4 | A complete blog system demonstrating: |
| 5 | - Create, read, update, delete posts |
| 6 | - Integration with auth system for authorization |
| 7 | - Search and filtering |
| 8 | - Pagination |
| 9 | - Author attribution |
| 10 | - Timestamps and versioning |
| 11 | - All in Object Primitive style |
| 12 | |
| 13 | Endpoints: |
| 14 | - GET /objects/advanced_blog - List posts (with pagination, filtering) |
| 15 | - GET /objects/advanced_blog?id=post123 - Get specific post |
| 16 | - POST /objects/advanced_blog - Create new post (requires auth token) |
| 17 | - PUT /objects/advanced_blog - Update post (requires auth token, must be author) |
| 18 | - DELETE /objects/advanced_blog - Delete post (requires auth token, must be author) |
| 19 | |
| 20 | This demonstrates how to build a blog WITHOUT using dbbasic-content |
| 21 | (which uses traditional class-based architecture). Instead, we use |
| 22 | Object Primitive patterns and integrate with our auth system. |
| 23 | """ |
| 24 | |
| 25 | import json |
| 26 | import time |
| 27 | import secrets |
| 28 | from typing import Dict, Any, List, Optional |
| 29 | |
| 30 | # Object Primitive dependencies (injected by runtime) |
| 31 | _logger = None |
| 32 | _state_manager = None |
| 33 | _runtime = None # Future: for calling other objects |
| 34 | |
| 35 | |
| 36 | def GET(request: Dict[str, Any]) -> Dict[str, Any]: |
| 37 | """ |
| 38 | Get post(s). |
| 39 | |
| 40 | Query params: |
| 41 | - id: Post ID to retrieve (if not provided, list all) |
| 42 | - author: Filter by author username |
| 43 | - search: Search in title and content |
| 44 | - limit: Number of posts to return (default 10, max 100) |
| 45 | - offset: Pagination offset (default 0) |
| 46 | - sort: Sort order (newest, oldest, title) (default newest) |
| 47 | |
| 48 | Returns: |
| 49 | - Single post if id provided |
| 50 | - List of posts otherwise |
| 51 | """ |
| 52 | post_id = request.get('id', '').strip() |
| 53 | author = request.get('author', '').strip() |
| 54 | search = request.get('search', '').strip().lower() |
| 55 | limit = min(int(request.get('limit', '10')), 100) |
| 56 | offset = int(request.get('offset', '0')) |
| 57 | sort = request.get('sort', 'newest') |
| 58 | |
| 59 | posts = _get_posts() |
| 60 | |
| 61 | # Get specific post |
| 62 | if post_id: |
| 63 | if post_id not in posts: |
| 64 | return {'status': 'error', 'message': f'Post not found: {post_id}'} |
| 65 | |
| 66 | post = posts[post_id] |
| 67 | if _logger: |
| 68 | _logger.info('Post viewed', post_id=post_id, title=post['title']) |
| 69 | |
| 70 | return { |
| 71 | 'status': 'ok', |
| 72 | 'post': { |
| 73 | 'id': post_id, |
| 74 | 'title': post['title'], |
| 75 | 'content': post['content'], |
| 76 | 'author': post['author'], |
| 77 | 'created_at': post['created_at'], |
| 78 | 'updated_at': post.get('updated_at', post['created_at']), |
| 79 | 'tags': post.get('tags', []), |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | # List posts with filtering |
| 84 | post_list = [] |
| 85 | for pid, post in posts.items(): |
| 86 | # Filter by author |
| 87 | if author and post['author'] != author: |
| 88 | continue |
| 89 | |
| 90 | # Filter by search term |
| 91 | if search: |
| 92 | if search not in post['title'].lower() and search not in post['content'].lower(): |
| 93 | continue |
| 94 | |
| 95 | post_list.append({ |
| 96 | 'id': pid, |
| 97 | 'title': post['title'], |
| 98 | 'excerpt': post['content'][:200] + ('...' if len(post['content']) > 200 else ''), |
| 99 | 'author': post['author'], |
| 100 | 'created_at': post['created_at'], |
| 101 | 'updated_at': post.get('updated_at', post['created_at']), |
| 102 | 'tags': post.get('tags', []), |
| 103 | }) |
| 104 | |
| 105 | # Sort posts |
| 106 | if sort == 'newest': |
| 107 | post_list.sort(key=lambda p: p['created_at'], reverse=True) |
| 108 | elif sort == 'oldest': |
| 109 | post_list.sort(key=lambda p: p['created_at']) |
| 110 | elif sort == 'title': |
| 111 | post_list.sort(key=lambda p: p['title'].lower()) |
| 112 | |
| 113 | # Pagination |
| 114 | total = len(post_list) |
| 115 | post_list = post_list[offset:offset + limit] |
| 116 | |
| 117 | if _logger: |
| 118 | _logger.info('Posts listed', count=len(post_list), total=total, author=author or 'all', search=search or 'none') |
| 119 | |
| 120 | return { |
| 121 | 'status': 'ok', |
| 122 | 'posts': post_list, |
| 123 | 'pagination': { |
| 124 | 'total': total, |
| 125 | 'limit': limit, |
| 126 | 'offset': offset, |
| 127 | 'has_more': offset + limit < total, |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | |
| 132 | def POST(request: Dict[str, Any]) -> Dict[str, Any]: |
| 133 | """ |
| 134 | Create a new blog post. |
| 135 | |
| 136 | Body (JSON): |
| 137 | { |
| 138 | "token": "auth_token_here", |
| 139 | "title": "My First Post", |
| 140 | "content": "This is the content...", |
| 141 | "tags": ["python", "tutorial"] // optional |
| 142 | } |
| 143 | |
| 144 | Returns: |
| 145 | - Post ID on success |
| 146 | - Error if unauthorized or validation fails |
| 147 | """ |
| 148 | token = request.get('token', '').strip() |
| 149 | title = request.get('title', '').strip() |
| 150 | content = request.get('content', '').strip() |
| 151 | tags = request.get('tags', []) |
| 152 | |
| 153 | # Validate token (simplified - in production, call auth object) |
| 154 | if not token: |
| 155 | return {'status': 'error', 'message': 'Authentication token required'} |
| 156 | |
| 157 | # In a real system, we'd call the auth object to validate the token |
| 158 | # For now, we'll use a simple check |
| 159 | # TODO: Integrate with auth object when _runtime injection is available |
| 160 | user_info = _validate_token_simple(token) |
| 161 | if not user_info: |
| 162 | if _logger: |
| 163 | _logger.warning('Unauthorized post creation attempt', token=token[:8]) |
| 164 | return {'status': 'error', 'message': 'Invalid or expired token'} |
| 165 | |
| 166 | # Validation |
| 167 | if not title: |
| 168 | return {'status': 'error', 'message': 'Title is required'} |
| 169 | |
| 170 | if len(title) > 200: |
| 171 | return {'status': 'error', 'message': 'Title must be 200 characters or less'} |
| 172 | |
| 173 | if not content: |
| 174 | return {'status': 'error', 'message': 'Content is required'} |
| 175 | |
| 176 | if len(content) > 100000: |
| 177 | return {'status': 'error', 'message': 'Content must be 100,000 characters or less'} |
| 178 | |
| 179 | # Create post |
| 180 | post_id = _generate_post_id() |
| 181 | posts = _get_posts() |
| 182 | |
| 183 | posts[post_id] = { |
| 184 | 'title': title, |
| 185 | 'content': content, |
| 186 | 'author': user_info['username'], |
| 187 | 'created_at': int(time.time()), |
| 188 | 'tags': tags if isinstance(tags, list) else [], |
| 189 | } |
| 190 | |
| 191 | _save_posts(posts) |
| 192 | |
| 193 | if _logger: |
| 194 | _logger.info('Post created', post_id=post_id, title=title, author=user_info['username']) |
| 195 | |
| 196 | return { |
| 197 | 'status': 'ok', |
| 198 | 'message': 'Post created', |
| 199 | 'post_id': post_id, |
| 200 | 'title': title, |
| 201 | } |
| 202 | |
| 203 | |
| 204 | def PUT(request: Dict[str, Any]) -> Dict[str, Any]: |
| 205 | """ |
| 206 | Update an existing blog post. |
| 207 | |
| 208 | Body (JSON): |
| 209 | { |
| 210 | "token": "auth_token_here", |
| 211 | "id": "post123", |
| 212 | "title": "Updated Title", // optional |
| 213 | "content": "Updated content", // optional |
| 214 | "tags": ["python", "web"] // optional |
| 215 | } |
| 216 | |
| 217 | Returns: |
| 218 | - Success message |
| 219 | - Error if unauthorized, not found, or not the author |
| 220 | """ |
| 221 | token = request.get('token', '').strip() |
| 222 | post_id = request.get('id', '').strip() |
| 223 | title = request.get('title', '').strip() |
| 224 | content = request.get('content', '').strip() |
| 225 | tags = request.get('tags') |
| 226 | |
| 227 | # Validate token |
| 228 | if not token: |
| 229 | return {'status': 'error', 'message': 'Authentication token required'} |
| 230 | |
| 231 | user_info = _validate_token_simple(token) |
| 232 | if not user_info: |
| 233 | if _logger: |
| 234 | _logger.warning('Unauthorized post update attempt', token=token[:8]) |
| 235 | return {'status': 'error', 'message': 'Invalid or expired token'} |
| 236 | |
| 237 | # Validate post ID |
| 238 | if not post_id: |
| 239 | return {'status': 'error', 'message': 'Post ID is required'} |
| 240 | |
| 241 | posts = _get_posts() |
| 242 | |
| 243 | if post_id not in posts: |
| 244 | return {'status': 'error', 'message': f'Post not found: {post_id}'} |
| 245 | |
| 246 | post = posts[post_id] |
| 247 | |
| 248 | # Check authorization (must be author) |
| 249 | if post['author'] != user_info['username']: |
| 250 | if _logger: |
| 251 | _logger.warning('Unauthorized post update', post_id=post_id, author=post['author'], attempted_by=user_info['username']) |
| 252 | return {'status': 'error', 'message': 'Only the author can update this post'} |
| 253 | |
| 254 | # Update fields |
| 255 | updated = False |
| 256 | |
| 257 | if title: |
| 258 | if len(title) > 200: |
| 259 | return {'status': 'error', 'message': 'Title must be 200 characters or less'} |
| 260 | post['title'] = title |
| 261 | updated = True |
| 262 | |
| 263 | if content: |
| 264 | if len(content) > 100000: |
| 265 | return {'status': 'error', 'message': 'Content must be 100,000 characters or less'} |
| 266 | post['content'] = content |
| 267 | updated = True |
| 268 | |
| 269 | if tags is not None: |
| 270 | if isinstance(tags, list): |
| 271 | post['tags'] = tags |
| 272 | updated = True |
| 273 | |
| 274 | if updated: |
| 275 | post['updated_at'] = int(time.time()) |
| 276 | _save_posts(posts) |
| 277 | |
| 278 | if _logger: |
| 279 | _logger.info('Post updated', post_id=post_id, title=post['title'], author=user_info['username']) |
| 280 | |
| 281 | return {'status': 'ok', 'message': 'Post updated', 'post_id': post_id} |
| 282 | else: |
| 283 | return {'status': 'ok', 'message': 'No changes'} |
| 284 | |
| 285 | |
| 286 | def DELETE(request: Dict[str, Any]) -> Dict[str, Any]: |
| 287 | """ |
| 288 | Delete a blog post. |
| 289 | |
| 290 | Query params: |
| 291 | - token: Authentication token |
| 292 | - id: Post ID to delete |
| 293 | |
| 294 | Returns: |
| 295 | - Success message |
| 296 | - Error if unauthorized, not found, or not the author |
| 297 | """ |
| 298 | token = request.get('token', '').strip() |
| 299 | post_id = request.get('id', '').strip() |
| 300 | |
| 301 | # Validate token |
| 302 | if not token: |
| 303 | return {'status': 'error', 'message': 'Authentication token required'} |
| 304 | |
| 305 | user_info = _validate_token_simple(token) |
| 306 | if not user_info: |
| 307 | if _logger: |
| 308 | _logger.warning('Unauthorized post deletion attempt', token=token[:8]) |
| 309 | return {'status': 'error', 'message': 'Invalid or expired token'} |
| 310 | |
| 311 | # Validate post ID |
| 312 | if not post_id: |
| 313 | return {'status': 'error', 'message': 'Post ID is required'} |
| 314 | |
| 315 | posts = _get_posts() |
| 316 | |
| 317 | if post_id not in posts: |
| 318 | return {'status': 'error', 'message': f'Post not found: {post_id}'} |
| 319 | |
| 320 | post = posts[post_id] |
| 321 | |
| 322 | # Check authorization (must be author or admin) |
| 323 | if post['author'] != user_info['username'] and not user_info.get('is_admin', False): |
| 324 | if _logger: |
| 325 | _logger.warning('Unauthorized post deletion', post_id=post_id, author=post['author'], attempted_by=user_info['username']) |
| 326 | return {'status': 'error', 'message': 'Only the author or admin can delete this post'} |
| 327 | |
| 328 | # Delete post |
| 329 | title = post['title'] |
| 330 | del posts[post_id] |
| 331 | _save_posts(posts) |
| 332 | |
| 333 | if _logger: |
| 334 | _logger.warning('Post deleted', post_id=post_id, title=title, author=post['author'], deleted_by=user_info['username']) |
| 335 | |
| 336 | return {'status': 'ok', 'message': f'Post deleted: {title}'} |
| 337 | |
| 338 | |
| 339 | # --- Internal Helper Functions --- |
| 340 | |
| 341 | def _get_posts() -> Dict[str, Any]: |
| 342 | """Get all posts from state.""" |
| 343 | if _state_manager: |
| 344 | posts_json = _state_manager.get('posts', '{}') |
| 345 | return json.loads(posts_json) |
| 346 | return {} |
| 347 | |
| 348 | |
| 349 | def _save_posts(posts: Dict[str, Any]): |
| 350 | """Save posts to state.""" |
| 351 | if _state_manager: |
| 352 | _state_manager.set('posts', json.dumps(posts)) |
| 353 | |
| 354 | |
| 355 | def _generate_post_id() -> str: |
| 356 | """Generate unique post ID.""" |
| 357 | return f'post_{int(time.time())}_{secrets.token_hex(4)}' |
| 358 | |
| 359 | |
| 360 | def _validate_token_simple(token: str) -> Optional[Dict[str, Any]]: |
| 361 | """ |
| 362 | Validate token by calling the auth object. |
| 363 | |
| 364 | Now that _runtime is available, we can call other objects! |
| 365 | """ |
| 366 | if not token: |
| 367 | return None |
| 368 | |
| 369 | # Call auth object to validate token |
| 370 | if _runtime: |
| 371 | try: |
| 372 | # Load auth object |
| 373 | auth_obj = _runtime.load_object('examples/advanced/auth.py') |
| 374 | |
| 375 | # Call GET with token to validate |
| 376 | result = auth_obj.execute('GET', {'token': token}) |
| 377 | |
| 378 | if result.get('status') == 'ok' and 'user' in result: |
| 379 | return result['user'] |
| 380 | except Exception as e: |
| 381 | # If auth object not available or error, fall back to mock |
| 382 | if _logger: |
| 383 | _logger.warning('Auth validation failed, using fallback', error=str(e)) |
| 384 | |
| 385 | # Fallback: Mock validation for demo purposes |
| 386 | if token and len(token) > 10: |
| 387 | return { |
| 388 | 'username': 'demo_user', |
| 389 | 'is_admin': False, |
| 390 | } |
| 391 | |
| 392 | return None |
| 393 | |
| 394 | |
| 395 | # Metadata for object introspection |
| 396 | __endpoint__ = { |
| 397 | 'name': 'Blog System', |
| 398 | 'description': 'Complete blog system in Object Primitive style', |
| 399 | 'version': '1.0.0', |
| 400 | 'author': 'Object Primitive System', |
| 401 | 'methods': ['GET', 'POST', 'PUT', 'DELETE'], |
| 402 | 'state_keys': ['posts'], |
| 403 | 'requires': ['auth'], # Depends on auth object |
| 404 | } |