Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.
dbbasic_route_display.py · 13.9 KB · 380 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | DBBasic Route Display |
| 4 | Shows all routes generated from DBBasic config files |
| 5 | """ |
| 6 | |
| 7 | import yaml |
| 8 | import json |
| 9 | from pathlib import Path |
| 10 | from typing import Dict, List, Any |
| 11 | from dataclasses import dataclass, asdict |
| 12 | from datetime import datetime |
| 13 | |
| 14 | @dataclass |
| 15 | class Route: |
| 16 | """Represents a single route in the system""" |
| 17 | path: str |
| 18 | method: str = "GET" |
| 19 | description: str = "" |
| 20 | source_type: str = "" # 'page', 'api', 'form', 'view', 'crud' |
| 21 | config_file: str = "" |
| 22 | auth_required: bool = False |
| 23 | params: List[str] = None |
| 24 | |
| 25 | def __post_init__(self): |
| 26 | if self.params is None: |
| 27 | self.params = [] |
| 28 | |
| 29 | class RouteExtractor: |
| 30 | """Extracts routes from DBBasic config files""" |
| 31 | |
| 32 | def __init__(self): |
| 33 | self.routes = [] |
| 34 | |
| 35 | def extract_from_config(self, config_path: str) -> List[Route]: |
| 36 | """Extract all routes from a DBBasic config file""" |
| 37 | with open(config_path, 'r') as f: |
| 38 | config = yaml.safe_load(f) |
| 39 | |
| 40 | if not config: |
| 41 | return [] |
| 42 | |
| 43 | routes = [] |
| 44 | config_name = Path(config_path).name |
| 45 | |
| 46 | # Extract from pages section |
| 47 | if 'pages' in config: |
| 48 | for path, page_config in config.get('pages', {}).items(): |
| 49 | if not path.startswith('/'): |
| 50 | path = '/' + path |
| 51 | |
| 52 | description = "Page" |
| 53 | if isinstance(page_config, dict): |
| 54 | description = page_config.get('description', 'Page') |
| 55 | auth = page_config.get('auth', False) |
| 56 | else: |
| 57 | auth = False |
| 58 | |
| 59 | routes.append(Route( |
| 60 | path=path, |
| 61 | method="GET", |
| 62 | description=description, |
| 63 | source_type="page", |
| 64 | config_file=config_name, |
| 65 | auth_required=auth |
| 66 | )) |
| 67 | |
| 68 | # Extract from API section |
| 69 | if 'api' in config: |
| 70 | for endpoint, api_config in config.get('api', {}).items(): |
| 71 | if not endpoint.startswith('/'): |
| 72 | endpoint = '/api/' + endpoint |
| 73 | elif not endpoint.startswith('/api'): |
| 74 | endpoint = '/api' + endpoint |
| 75 | |
| 76 | if isinstance(api_config, dict): |
| 77 | # Handle multiple HTTP methods |
| 78 | if 'operations' in api_config: |
| 79 | for method, desc in api_config['operations'].items(): |
| 80 | routes.append(Route( |
| 81 | path=endpoint, |
| 82 | method=method.upper(), |
| 83 | description=desc, |
| 84 | source_type="api", |
| 85 | config_file=config_name, |
| 86 | auth_required=api_config.get('security', {}).get('auth', False) |
| 87 | )) |
| 88 | else: |
| 89 | # Single method API |
| 90 | method = api_config.get('method', 'GET') |
| 91 | routes.append(Route( |
| 92 | path=endpoint, |
| 93 | method=method.upper(), |
| 94 | description=api_config.get('description', 'API endpoint'), |
| 95 | source_type="api", |
| 96 | config_file=config_name, |
| 97 | auth_required=api_config.get('auth', False) |
| 98 | )) |
| 99 | |
| 100 | # Extract from forms section |
| 101 | if 'forms' in config: |
| 102 | for form_name, form_config in config.get('forms', {}).items(): |
| 103 | # Forms typically generate both GET (display) and POST (submit) routes |
| 104 | path = f"/forms/{form_name}" |
| 105 | |
| 106 | routes.append(Route( |
| 107 | path=path, |
| 108 | method="GET", |
| 109 | description=f"Display {form_name} form", |
| 110 | source_type="form", |
| 111 | config_file=config_name |
| 112 | )) |
| 113 | |
| 114 | routes.append(Route( |
| 115 | path=path, |
| 116 | method="POST", |
| 117 | description=f"Submit {form_name} form", |
| 118 | source_type="form", |
| 119 | config_file=config_name |
| 120 | )) |
| 121 | |
| 122 | # Extract CRUD routes from data/model section |
| 123 | if 'data' in config or 'model' in config: |
| 124 | data_section = config.get('data', config.get('model', {})) |
| 125 | for entity_name, entity_config in data_section.items(): |
| 126 | if isinstance(entity_config, dict) or isinstance(entity_config, list): |
| 127 | # Generate standard CRUD routes |
| 128 | base_path = f"/api/{entity_name}" |
| 129 | |
| 130 | routes.extend([ |
| 131 | Route( |
| 132 | path=base_path, |
| 133 | method="GET", |
| 134 | description=f"List all {entity_name}", |
| 135 | source_type="crud", |
| 136 | config_file=config_name |
| 137 | ), |
| 138 | Route( |
| 139 | path=base_path, |
| 140 | method="POST", |
| 141 | description=f"Create new {entity_name}", |
| 142 | source_type="crud", |
| 143 | config_file=config_name |
| 144 | ), |
| 145 | Route( |
| 146 | path=f"{base_path}/{{id}}", |
| 147 | method="GET", |
| 148 | description=f"Get {entity_name} by ID", |
| 149 | source_type="crud", |
| 150 | config_file=config_name, |
| 151 | params=["id"] |
| 152 | ), |
| 153 | Route( |
| 154 | path=f"{base_path}/{{id}}", |
| 155 | method="PUT", |
| 156 | description=f"Update {entity_name}", |
| 157 | source_type="crud", |
| 158 | config_file=config_name, |
| 159 | params=["id"] |
| 160 | ), |
| 161 | Route( |
| 162 | path=f"{base_path}/{{id}}", |
| 163 | method="DELETE", |
| 164 | description=f"Delete {entity_name}", |
| 165 | source_type="crud", |
| 166 | config_file=config_name, |
| 167 | params=["id"] |
| 168 | ) |
| 169 | ]) |
| 170 | |
| 171 | # Extract from views section (typically read-only endpoints) |
| 172 | if 'views' in config: |
| 173 | for view_name, view_config in config.get('views', {}).items(): |
| 174 | path = f"/views/{view_name}" |
| 175 | |
| 176 | if isinstance(view_config, str): |
| 177 | # Simple SQL view |
| 178 | description = f"View: {view_name}" |
| 179 | elif isinstance(view_config, dict): |
| 180 | description = view_config.get('description', f"View: {view_name}") |
| 181 | else: |
| 182 | description = f"View: {view_name}" |
| 183 | |
| 184 | routes.append(Route( |
| 185 | path=path, |
| 186 | method="GET", |
| 187 | description=description, |
| 188 | source_type="view", |
| 189 | config_file=config_name |
| 190 | )) |
| 191 | |
| 192 | return routes |
| 193 | |
| 194 | def extract_from_directory(self, directory: str = ".") -> List[Route]: |
| 195 | """Extract routes from all DBBasic config files in a directory""" |
| 196 | all_routes = [] |
| 197 | |
| 198 | # Look for .dbbasic and .yaml files that appear to be DBBasic configs |
| 199 | for config_file in Path(directory).glob("*.dbbasic"): |
| 200 | all_routes.extend(self.extract_from_config(str(config_file))) |
| 201 | |
| 202 | for config_file in Path(directory).glob("*.yaml"): |
| 203 | # Check if it looks like a DBBasic config |
| 204 | try: |
| 205 | with open(config_file, 'r') as f: |
| 206 | content = yaml.safe_load(f) |
| 207 | if content and any(key in content for key in ['pages', 'api', 'data', 'model', 'forms', 'views']): |
| 208 | all_routes.extend(self.extract_from_config(str(config_file))) |
| 209 | except: |
| 210 | pass |
| 211 | |
| 212 | return all_routes |
| 213 | |
| 214 | class RouteDisplay: |
| 215 | """Display routes in various formats""" |
| 216 | |
| 217 | @staticmethod |
| 218 | def as_table(routes: List[Route]) -> str: |
| 219 | """Display routes as a formatted table""" |
| 220 | if not routes: |
| 221 | return "No routes found." |
| 222 | |
| 223 | # Calculate column widths |
| 224 | method_width = max(len(r.method) for r in routes) + 2 |
| 225 | path_width = max(len(r.path) for r in routes) + 2 |
| 226 | desc_width = max(len(r.description) for r in routes if r.description) + 2 |
| 227 | type_width = max(len(r.source_type) for r in routes) + 2 |
| 228 | |
| 229 | # Limit widths for readability |
| 230 | path_width = min(path_width, 40) |
| 231 | desc_width = min(desc_width, 40) |
| 232 | |
| 233 | # Header |
| 234 | output = [] |
| 235 | output.append("=" * (method_width + path_width + desc_width + type_width + 10)) |
| 236 | output.append(f"{'Method':<{method_width}} {'Path':<{path_width}} {'Type':<{type_width}} {'Description':<{desc_width}}") |
| 237 | output.append("=" * (method_width + path_width + desc_width + type_width + 10)) |
| 238 | |
| 239 | # Routes |
| 240 | for route in sorted(routes, key=lambda r: (r.path, r.method)): |
| 241 | path = route.path[:path_width-2] if len(route.path) > path_width-2 else route.path |
| 242 | desc = route.description[:desc_width-2] if len(route.description) > desc_width-2 else route.description |
| 243 | output.append( |
| 244 | f"{route.method:<{method_width}} {path:<{path_width}} {route.source_type:<{type_width}} {desc:<{desc_width}}" |
| 245 | ) |
| 246 | |
| 247 | output.append("=" * (method_width + path_width + desc_width + type_width + 10)) |
| 248 | output.append(f"Total: {len(routes)} routes") |
| 249 | |
| 250 | return "\n".join(output) |
| 251 | |
| 252 | @staticmethod |
| 253 | def as_markdown(routes: List[Route]) -> str: |
| 254 | """Display routes as markdown table""" |
| 255 | if not routes: |
| 256 | return "No routes found." |
| 257 | |
| 258 | output = [] |
| 259 | output.append("# DBBasic Routes") |
| 260 | output.append("") |
| 261 | output.append("| Method | Path | Type | Description | Auth | Config |") |
| 262 | output.append("|--------|------|------|-------------|------|--------|") |
| 263 | |
| 264 | for route in sorted(routes, key=lambda r: (r.path, r.method)): |
| 265 | auth = "✓" if route.auth_required else "" |
| 266 | output.append( |
| 267 | f"| {route.method} | {route.path} | {route.source_type} | {route.description} | {auth} | {route.config_file} |" |
| 268 | ) |
| 269 | |
| 270 | output.append("") |
| 271 | output.append(f"**Total: {len(routes)} routes**") |
| 272 | |
| 273 | return "\n".join(output) |
| 274 | |
| 275 | @staticmethod |
| 276 | def as_json(routes: List[Route]) -> str: |
| 277 | """Export routes as JSON""" |
| 278 | routes_dict = [ |
| 279 | asdict(route) for route in sorted(routes, key=lambda r: (r.path, r.method)) |
| 280 | ] |
| 281 | return json.dumps(routes_dict, indent=2) |
| 282 | |
| 283 | @staticmethod |
| 284 | def as_openapi_snippet(routes: List[Route]) -> str: |
| 285 | """Generate OpenAPI specification snippet""" |
| 286 | paths = {} |
| 287 | |
| 288 | for route in routes: |
| 289 | if route.path not in paths: |
| 290 | paths[route.path] = {} |
| 291 | |
| 292 | operation = { |
| 293 | "summary": route.description, |
| 294 | "tags": [route.source_type], |
| 295 | "responses": { |
| 296 | "200": {"description": "Success"} |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | if route.auth_required: |
| 301 | operation["security"] = [{"bearerAuth": []}] |
| 302 | |
| 303 | if route.params: |
| 304 | operation["parameters"] = [ |
| 305 | { |
| 306 | "name": param, |
| 307 | "in": "path", |
| 308 | "required": True, |
| 309 | "schema": {"type": "string"} |
| 310 | } |
| 311 | for param in route.params |
| 312 | ] |
| 313 | |
| 314 | paths[route.path][route.method.lower()] = operation |
| 315 | |
| 316 | openapi = { |
| 317 | "openapi": "3.0.0", |
| 318 | "info": { |
| 319 | "title": "DBBasic API", |
| 320 | "version": "1.0.0", |
| 321 | "description": "Routes generated from DBBasic config" |
| 322 | }, |
| 323 | "paths": paths |
| 324 | } |
| 325 | |
| 326 | return yaml.dump(openapi, default_flow_style=False) |
| 327 | |
| 328 | def main(): |
| 329 | """Main CLI interface""" |
| 330 | import argparse |
| 331 | |
| 332 | parser = argparse.ArgumentParser(description="Display routes from DBBasic config files") |
| 333 | parser.add_argument( |
| 334 | "path", |
| 335 | nargs="?", |
| 336 | default=".", |
| 337 | help="Path to config file or directory (default: current directory)" |
| 338 | ) |
| 339 | parser.add_argument( |
| 340 | "-f", "--format", |
| 341 | choices=["table", "markdown", "json", "openapi"], |
| 342 | default="table", |
| 343 | help="Output format (default: table)" |
| 344 | ) |
| 345 | parser.add_argument( |
| 346 | "-o", "--output", |
| 347 | help="Output file (default: stdout)" |
| 348 | ) |
| 349 | |
| 350 | args = parser.parse_args() |
| 351 | |
| 352 | extractor = RouteExtractor() |
| 353 | |
| 354 | # Extract routes |
| 355 | path = Path(args.path) |
| 356 | if path.is_file(): |
| 357 | routes = extractor.extract_from_config(str(path)) |
| 358 | else: |
| 359 | routes = extractor.extract_from_directory(str(path)) |
| 360 | |
| 361 | # Format output |
| 362 | if args.format == "table": |
| 363 | output = RouteDisplay.as_table(routes) |
| 364 | elif args.format == "markdown": |
| 365 | output = RouteDisplay.as_markdown(routes) |
| 366 | elif args.format == "json": |
| 367 | output = RouteDisplay.as_json(routes) |
| 368 | elif args.format == "openapi": |
| 369 | output = RouteDisplay.as_openapi_snippet(routes) |
| 370 | |
| 371 | # Write output |
| 372 | if args.output: |
| 373 | with open(args.output, 'w') as f: |
| 374 | f.write(output) |
| 375 | print(f"Routes written to {args.output}") |
| 376 | else: |
| 377 | print(output) |
| 378 | |
| 379 | if __name__ == "__main__": |
| 380 | main() |