runapi 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
runapi/cli.py ADDED
@@ -0,0 +1,576 @@
1
+ # runapi/cli.py
2
+ import typer
3
+ import uvicorn
4
+ from rich.console import Console
5
+ from rich.table import Table
6
+ from rich.panel import Panel
7
+ from rich.text import Text
8
+ from pathlib import Path
9
+ import os
10
+ import shutil
11
+ from typing import Optional
12
+
13
+ from .config import load_config, RunApiConfig
14
+ from .core import create_runapi_app
15
+
16
+ app = typer.Typer(name="runapi", help="RunApi - Next.js-inspired Python Backend Framework")
17
+ console = Console()
18
+
19
+
20
+ @app.command()
21
+ def dev(
22
+ host: str = typer.Option(None, "--host", "-h", help="Host to bind"),
23
+ port: int = typer.Option(None, "--port", "-p", help="Port to bind"),
24
+ reload: bool = typer.Option(None, "--reload/--no-reload", help="Enable auto-reload"),
25
+ config_file: str = typer.Option(".env", "--config", "-c", help="Configuration file"),
26
+ log_level: str = typer.Option(None, "--log-level", "-l", help="Log level"),
27
+ ):
28
+ """Run the RunApi development server."""
29
+ console.print(Panel.fit("🚀 [bold blue]RunApi Development Server[/bold blue]", style="blue"))
30
+
31
+ # Load configuration
32
+ config = load_config(config_file)
33
+
34
+ # Override config with CLI arguments if provided
35
+ if host:
36
+ config.host = host
37
+ if port:
38
+ config.port = port
39
+ if reload is not None:
40
+ config.reload = reload
41
+ if log_level:
42
+ config.log_level = log_level
43
+
44
+ # Check if main.py exists
45
+ main_path = Path("main.py")
46
+ if not main_path.exists():
47
+ console.print("[red]❌ Error: main.py not found in current directory")
48
+ console.print("[yellow]💡 Tip: Run 'runapi init' to create a new project or 'runapi generate main' to create main.py")
49
+ raise typer.Exit(code=1)
50
+
51
+ # Display server info
52
+ table = Table(show_header=False, box=None)
53
+ table.add_row("🌐 Server:", f"http://{config.host}:{config.port}")
54
+ table.add_row("🔄 Reload:", "✅ Enabled" if config.reload else "❌ Disabled")
55
+ table.add_row("📝 Log Level:", config.log_level.upper())
56
+ table.add_row("âš™ī¸ Config:", config_file if Path(config_file).exists() else "Default")
57
+ console.print(table)
58
+
59
+ # Check for routes directory
60
+ routes_path = Path("routes")
61
+ if routes_path.exists():
62
+ route_count = len([f for f in routes_path.rglob("*.py") if f.name != "__init__.py"])
63
+ console.print(f"📁 Found {route_count} route files in ./routes/")
64
+ else:
65
+ console.print("[yellow]âš ī¸ No routes directory found")
66
+
67
+ console.print()
68
+
69
+ try:
70
+ # Run uvicorn with the FastAPI app
71
+ uvicorn.run(
72
+ "main:app",
73
+ host=config.host,
74
+ port=config.port,
75
+ reload=config.reload,
76
+ log_level=config.log_level.lower(),
77
+ )
78
+ except KeyboardInterrupt:
79
+ console.print("\n[yellow]👋 Server stopped")
80
+
81
+
82
+ @app.command()
83
+ def init(
84
+ name: str = typer.Argument(..., help="Project name"),
85
+ template: str = typer.Option("basic", "--template", "-t", help="Project template"),
86
+ ):
87
+ """Initialize a new RunApi project."""
88
+ project_path = Path(name)
89
+
90
+ if project_path.exists():
91
+ console.print(f"[red]❌ Directory '{name}' already exists")
92
+ raise typer.Exit(code=1)
93
+
94
+ console.print(f"🚀 [bold blue]Creating RunApi project: {name}[/bold blue]")
95
+
96
+ # Create project directory
97
+ project_path.mkdir()
98
+
99
+ # Create basic project structure
100
+ (project_path / "routes").mkdir()
101
+ (project_path / "routes" / "__init__.py").touch()
102
+ (project_path / "static").mkdir()
103
+ (project_path / "uploads").mkdir()
104
+
105
+ # Create main.py
106
+ main_content = '''"""
107
+ RunApi Application Entry Point
108
+ """
109
+ from runapi import create_runapi_app
110
+
111
+ # Create RunApi application
112
+ runapi_app = create_runapi_app(
113
+ title="My RunApi API",
114
+ description="Built with RunApi framework",
115
+ version="1.0.0"
116
+ )
117
+
118
+ # Get FastAPI app for uvicorn
119
+ app = runapi_app.get_app()
120
+
121
+ if __name__ == "__main__":
122
+ runapi_app.run()
123
+ '''
124
+
125
+ (project_path / "main.py").write_text(main_content, encoding='utf-8')
126
+
127
+ # Create example route
128
+ routes_api_path = project_path / "routes" / "api"
129
+ routes_api_path.mkdir()
130
+ (routes_api_path / "__init__.py").touch()
131
+
132
+ example_route = '''"""
133
+ Example API route
134
+ GET /api/hello
135
+ """
136
+ from runapi import JSONResponse
137
+
138
+ async def get():
139
+ return JSONResponse({
140
+ "message": "Hello from RunApi!",
141
+ "framework": "RunApi",
142
+ "status": "success"
143
+ })
144
+ '''
145
+
146
+ (routes_api_path / "hello.py").write_text(example_route, encoding='utf-8')
147
+
148
+ # Create index route
149
+ index_route = '''"""
150
+ Home page route
151
+ GET /
152
+ """
153
+ from runapi import JSONResponse
154
+
155
+ async def get():
156
+ return JSONResponse({
157
+ "message": "Welcome to RunApi!",
158
+ "docs": "/docs",
159
+ "routes": {
160
+ "hello": "/api/hello"
161
+ }
162
+ })
163
+ '''
164
+
165
+ (project_path / "routes" / "index.py").write_text(index_route, encoding='utf-8')
166
+
167
+ # Create .env file
168
+ env_content = '''# RunApi Configuration
169
+ DEBUG=true
170
+ HOST=127.0.0.1
171
+ PORT=8000
172
+ SECRET_KEY=dev-secret-key-change-in-production
173
+
174
+ # CORS Settings
175
+ CORS_ORIGINS=*
176
+ CORS_CREDENTIALS=true
177
+
178
+ # Rate Limiting
179
+ RATE_LIMIT_ENABLED=false
180
+ RATE_LIMIT_CALLS=100
181
+ RATE_LIMIT_PERIOD=60
182
+
183
+ # Logging
184
+ LOG_LEVEL=INFO
185
+
186
+ # Static Files
187
+ STATIC_FILES_ENABLED=true
188
+ STATIC_FILES_PATH=static
189
+ STATIC_FILES_URL=/static
190
+ '''
191
+
192
+ (project_path / ".env").write_text(env_content, encoding='utf-8')
193
+
194
+ # Create .gitignore
195
+ gitignore_content = '''# Python
196
+ __pycache__/
197
+ *.py[cod]
198
+ *$py.class
199
+ *.so
200
+ .Python
201
+ env/
202
+ venv/
203
+ ENV/
204
+ env.bak/
205
+ venv.bak/
206
+
207
+ # RunApi
208
+ .env
209
+ uploads/
210
+ *.log
211
+
212
+ # IDE
213
+ .vscode/
214
+ .idea/
215
+ *.swp
216
+ *.swo
217
+
218
+ # OS
219
+ .DS_Store
220
+ Thumbs.db
221
+ '''
222
+
223
+ (project_path / ".gitignore").write_text(gitignore_content, encoding='utf-8')
224
+
225
+ # Create README
226
+ readme_content = f'''# {name}
227
+
228
+ A RunApi API project.
229
+
230
+ ## Getting Started
231
+
232
+ 1. Install dependencies:
233
+ ```bash
234
+ pip install runapi
235
+ ```
236
+
237
+ 2. Run development server:
238
+ ```bash
239
+ cd {name}
240
+ runapi dev
241
+ ```
242
+
243
+ 3. Open http://localhost:8000
244
+
245
+ ## Project Structure
246
+
247
+ ```
248
+ {name}/
249
+ ├── routes/ # API routes (file-based routing)
250
+ │ ├── index.py # GET /
251
+ │ └── api/
252
+ │ └── hello.py # GET /api/hello
253
+ ├── static/ # Static files
254
+ ├── uploads/ # File uploads
255
+ ├── main.py # Application entry point
256
+ └── .env # Configuration
257
+ ```
258
+
259
+ ## Available Routes
260
+
261
+ - `GET /` - Home page
262
+ - `GET /api/hello` - Example API endpoint
263
+ - `GET /docs` - API documentation
264
+
265
+ ## Adding Routes
266
+
267
+ Create Python files in the `routes/` directory:
268
+
269
+ - `routes/users.py` -> `GET /users`
270
+ - `routes/api/users/[id].py` -> `GET /api/users/123`
271
+ - `routes/api/auth/login.py` -> `GET /api/auth/login`
272
+
273
+ Export HTTP method functions:
274
+
275
+ ```python
276
+ async def get():
277
+ return {{"message": "GET request"}}
278
+
279
+ async def post():
280
+ return {{"message": "POST request"}}
281
+ ```
282
+ '''
283
+
284
+ (project_path / "README.md").write_text(readme_content, encoding='utf-8')
285
+
286
+ console.print("✅ [green]Project created successfully!")
287
+ console.print(f"\n📁 Project structure:")
288
+
289
+ # Show project structure
290
+ for root, dirs, files in os.walk(project_path):
291
+ level = root.replace(str(project_path), '').count(os.sep)
292
+ indent = ' ' * 2 * level
293
+ console.print(f"{indent}{os.path.basename(root)}/")
294
+ subindent = ' ' * 2 * (level + 1)
295
+ for file in files:
296
+ console.print(f"{subindent}{file}")
297
+
298
+ console.print(f"\n🚀 To get started:")
299
+ console.print(f" cd {name}")
300
+ console.print(f" runapi dev")
301
+
302
+
303
+ @app.command()
304
+ def generate(
305
+ item: str = typer.Argument(..., help="What to generate (route, main, middleware)"),
306
+ name: str = typer.Argument(..., help="Name of the item"),
307
+ path: str = typer.Option("", "--path", "-p", help="Path for the item"),
308
+ ):
309
+ """Generate boilerplate code."""
310
+ if item == "route":
311
+ _generate_route(name, path)
312
+ elif item == "main":
313
+ _generate_main()
314
+ elif item == "middleware":
315
+ _generate_middleware(name)
316
+ else:
317
+ console.print(f"[red]❌ Unknown generator: {item}")
318
+ console.print("Available generators: route, main, middleware")
319
+ raise typer.Exit(code=1)
320
+
321
+
322
+ def _generate_route(name: str, path: str):
323
+ """Generate a new route file."""
324
+ routes_path = Path("routes")
325
+ if not routes_path.exists():
326
+ routes_path.mkdir()
327
+ (routes_path / "__init__.py").touch()
328
+
329
+ if path:
330
+ route_path = routes_path / path
331
+ route_path.mkdir(parents=True, exist_ok=True)
332
+ (route_path / "__init__.py").touch()
333
+ file_path = route_path / f"{name}.py"
334
+ else:
335
+ file_path = routes_path / f"{name}.py"
336
+
337
+ if file_path.exists():
338
+ console.print(f"[red]❌ Route already exists: {file_path}")
339
+ raise typer.Exit(code=1)
340
+
341
+ # Generate route template
342
+ route_template = f'''"""
343
+ {name.title()} route
344
+ Generated by RunApi CLI
345
+ """
346
+ from runapi import JSONResponse, HTTPException, Request
347
+
348
+ async def get(request: Request):
349
+ """Handle GET request."""
350
+ return JSONResponse({{
351
+ "message": "Hello from {name}!",
352
+ "method": "GET",
353
+ "path": str(request.url.path)
354
+ }})
355
+
356
+ async def post(request: Request):
357
+ """Handle POST request."""
358
+ # Get request body
359
+ body = await request.json()
360
+
361
+ return JSONResponse({{
362
+ "message": "Data received",
363
+ "method": "POST",
364
+ "data": body
365
+ }})
366
+
367
+ # Uncomment and implement other HTTP methods as needed:
368
+
369
+ # async def put(request: Request):
370
+ # """Handle PUT request."""
371
+ # pass
372
+
373
+ # async def delete(request: Request):
374
+ # """Handle DELETE request."""
375
+ # pass
376
+
377
+ # async def patch(request: Request):
378
+ # """Handle PATCH request."""
379
+ # pass
380
+ '''
381
+
382
+ file_path.write_text(route_template, encoding='utf-8')
383
+ console.print(f"✅ [green]Route created: {file_path}")
384
+
385
+ # Show URL mapping
386
+ route_url = "/" + str(file_path.relative_to(routes_path)).replace("\\", "/").replace(".py", "")
387
+ if route_url.endswith("/index"):
388
+ route_url = route_url[:-6] or "/"
389
+ console.print(f"🌐 URL: {route_url}")
390
+
391
+
392
+ def _generate_main():
393
+ """Generate main.py file."""
394
+ main_path = Path("main.py")
395
+ if main_path.exists():
396
+ if not typer.confirm("main.py already exists. Overwrite?"):
397
+ raise typer.Exit()
398
+
399
+ main_content = '''"""
400
+ RunApi Application Entry Point
401
+ """
402
+ from runapi import create_runapi_app, get_config
403
+
404
+ # Load configuration
405
+ config = get_config()
406
+
407
+ # Create RunApi application
408
+ runapi_app = create_runapi_app(
409
+ title="My RunApi API",
410
+ description="Built with RunApi framework",
411
+ version="1.0.0"
412
+ )
413
+
414
+ # Add custom middleware if needed
415
+ # runapi_app.add_auth_middleware(protected_paths=["/api/protected"])
416
+
417
+ # Get FastAPI app for uvicorn
418
+ app = runapi_app.get_app()
419
+
420
+ if __name__ == "__main__":
421
+ runapi_app.run()
422
+ '''
423
+
424
+ main_path.write_text(main_content, encoding='utf-8')
425
+ console.print("✅ [green]main.py created successfully!")
426
+
427
+
428
+ def _generate_middleware(name: str):
429
+ """Generate a custom middleware file."""
430
+ middleware_path = Path("middleware")
431
+ middleware_path.mkdir(exist_ok=True)
432
+ (middleware_path / "__init__.py").touch()
433
+
434
+ file_path = middleware_path / f"{name}.py"
435
+
436
+ if file_path.exists():
437
+ console.print(f"[red]❌ Middleware already exists: {file_path}")
438
+ raise typer.Exit(code=1)
439
+
440
+ middleware_template = f'''"""
441
+ {name.title()} middleware
442
+ Generated by RunApi CLI
443
+ """
444
+ from runapi import RunApiMiddleware, Request, Response
445
+ from typing import Callable
446
+
447
+ class {name.title()}Middleware(RunApiMiddleware):
448
+ """Custom {name} middleware."""
449
+
450
+ def __init__(self, app, **kwargs):
451
+ super().__init__(app)
452
+ # Initialize middleware parameters
453
+ pass
454
+
455
+ async def dispatch(self, request: Request, call_next: Callable) -> Response:
456
+ """Process request and response."""
457
+ # Pre-processing
458
+ print(f"Processing request: {{request.method}} {{request.url.path}}")
459
+
460
+ # Call next middleware/route
461
+ response = await call_next(request)
462
+
463
+ # Post-processing
464
+ print(f"Response status: {{response.status_code}}")
465
+
466
+ return response
467
+
468
+ # Usage in main.py:
469
+ # from middleware.{name} import {name.title()}Middleware
470
+ # runapi_app.add_middleware({name.title()}Middleware)
471
+ '''
472
+
473
+ file_path.write_text(middleware_template, encoding='utf-8')
474
+ console.print(f"✅ [green]Middleware created: {file_path}")
475
+
476
+
477
+ @app.command()
478
+ def routes():
479
+ """List all available routes in the project."""
480
+ routes_path = Path("routes")
481
+ if not routes_path.exists():
482
+ console.print("[red]❌ No routes directory found")
483
+ raise typer.Exit(code=1)
484
+
485
+ console.print("📋 [bold blue]Available Routes[/bold blue]\n")
486
+
487
+ table = Table(show_header=True, header_style="bold blue")
488
+ table.add_column("Method")
489
+ table.add_column("Path")
490
+ table.add_column("File")
491
+
492
+ for route_file in routes_path.rglob("*.py"):
493
+ if route_file.name == "__init__.py":
494
+ continue
495
+
496
+ # Generate URL path
497
+ relative_path = route_file.relative_to(routes_path)
498
+ url_path = "/" + str(relative_path).replace("\\", "/").replace(".py", "")
499
+
500
+ if url_path.endswith("/index"):
501
+ url_path = url_path[:-6] or "/"
502
+
503
+ # Check for dynamic routes
504
+ if "[" in url_path and "]" in url_path:
505
+ # Convert [id] to {id}
506
+ import re
507
+ url_path = re.sub(r'\[([^\]]+)\]', r'{\1}', url_path)
508
+
509
+ # Read file to detect HTTP methods
510
+ try:
511
+ content = route_file.read_text()
512
+ methods = []
513
+ for method in ["get", "post", "put", "delete", "patch", "head", "options"]:
514
+ if f"async def {method}(" in content or f"def {method}(" in content:
515
+ methods.append(method.upper())
516
+
517
+ methods_str = ", ".join(methods) if methods else "No methods found"
518
+ table.add_row(methods_str, url_path, str(relative_path))
519
+
520
+ except Exception as e:
521
+ table.add_row("Error", url_path, f"Error reading file: {e}")
522
+
523
+ console.print(table)
524
+
525
+
526
+ @app.command()
527
+ def info():
528
+ """Show project information and configuration."""
529
+ console.print("â„šī¸ [bold blue]RunApi Project Information[/bold blue]\n")
530
+
531
+ # Load config
532
+ config = load_config()
533
+
534
+ # Project info
535
+ info_table = Table(show_header=False, box=None)
536
+ info_table.add_row("📁 Project Directory:", str(Path.cwd()))
537
+ info_table.add_row("🐍 RunApi Version:", "0.1.0")
538
+
539
+ # Check main.py
540
+ if Path("main.py").exists():
541
+ info_table.add_row("📄 Entry Point:", "main.py ✅")
542
+ else:
543
+ info_table.add_row("📄 Entry Point:", "main.py ❌")
544
+
545
+ # Check routes
546
+ routes_path = Path("routes")
547
+ if routes_path.exists():
548
+ route_count = len([f for f in routes_path.rglob("*.py") if f.name != "__init__.py"])
549
+ info_table.add_row("đŸ›Ŗī¸ Routes:", f"{route_count} files")
550
+ else:
551
+ info_table.add_row("đŸ›Ŗī¸ Routes:", "No routes directory")
552
+
553
+ console.print(info_table)
554
+ console.print()
555
+
556
+ # Configuration
557
+ config_table = Table(show_header=True, header_style="bold blue", title="Configuration")
558
+ config_table.add_column("Setting")
559
+ config_table.add_column("Value")
560
+
561
+ config_table.add_row("Debug", "✅ Enabled" if config.debug else "❌ Disabled")
562
+ config_table.add_row("Host", config.host)
563
+ config_table.add_row("Port", str(config.port))
564
+ config_table.add_row("CORS Origins", ", ".join(config.cors_origins))
565
+ config_table.add_row("Rate Limiting", "✅ Enabled" if config.rate_limit_enabled else "❌ Disabled")
566
+ config_table.add_row("Log Level", config.log_level)
567
+
568
+ console.print(config_table)
569
+
570
+
571
+ def main():
572
+ """Main entry point for CLI."""
573
+ app()
574
+
575
+ if __name__ == "__main__":
576
+ main()