runapi 0.2.0__tar.gz → 0.3.0__tar.gz

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.
Files changed (50) hide show
  1. {runapi-0.2.0 → runapi-0.3.0}/.gitignore +3 -0
  2. {runapi-0.2.0 → runapi-0.3.0}/PKG-INFO +6 -1
  3. {runapi-0.2.0 → runapi-0.3.0}/pyproject.toml +7 -1
  4. {runapi-0.2.0 → runapi-0.3.0}/runapi/__init__.py +18 -0
  5. {runapi-0.2.0 → runapi-0.3.0}/runapi/_version.py +2 -2
  6. {runapi-0.2.0 → runapi-0.3.0}/runapi/auth.py +10 -29
  7. runapi-0.3.0/runapi/backends.py +156 -0
  8. runapi-0.3.0/runapi/cli/__init__.py +53 -0
  9. runapi-0.3.0/runapi/cli/_app.py +7 -0
  10. runapi-0.3.0/runapi/cli/_templates.py +28 -0
  11. runapi-0.3.0/runapi/cli/commands/__init__.py +1 -0
  12. runapi-0.3.0/runapi/cli/commands/db.py +69 -0
  13. runapi-0.3.0/runapi/cli/commands/generate.py +153 -0
  14. runapi-0.3.0/runapi/cli/commands/inspect.py +214 -0
  15. runapi-0.3.0/runapi/cli/commands/project.py +74 -0
  16. runapi-0.3.0/runapi/cli/commands/server.py +186 -0
  17. runapi-0.3.0/runapi/cli/templates/generate/crud_index.py.tmpl +19 -0
  18. runapi-0.3.0/runapi/cli/templates/generate/crud_item.py.tmpl +20 -0
  19. runapi-0.3.0/runapi/cli/templates/generate/crud_service_footer.py.tmpl +14 -0
  20. runapi-0.3.0/runapi/cli/templates/generate/main.py.tmpl +23 -0
  21. runapi-0.3.0/runapi/cli/templates/generate/middleware.py.tmpl +31 -0
  22. runapi-0.3.0/runapi/cli/templates/generate/repository.py.tmpl +72 -0
  23. runapi-0.3.0/runapi/cli/templates/generate/route.py.tmpl +38 -0
  24. runapi-0.3.0/runapi/cli/templates/generate/schema.py.tmpl +49 -0
  25. runapi-0.3.0/runapi/cli/templates/generate/service.py.tmpl +101 -0
  26. runapi-0.3.0/runapi/cli/templates/project/Dockerfile.tmpl +16 -0
  27. runapi-0.3.0/runapi/cli/templates/project/README.md.tmpl +56 -0
  28. runapi-0.3.0/runapi/cli/templates/project/dockerignore.tmpl +5 -0
  29. runapi-0.3.0/runapi/cli/templates/project/env.tmpl +23 -0
  30. runapi-0.3.0/runapi/cli/templates/project/gitignore.tmpl +26 -0
  31. runapi-0.3.0/runapi/cli/templates/project/main.py.tmpl +17 -0
  32. runapi-0.3.0/runapi/cli/templates/project/route_hello.py.tmpl +12 -0
  33. runapi-0.3.0/runapi/cli/templates/project/route_index.py.tmpl +14 -0
  34. runapi-0.3.0/runapi/config.py +188 -0
  35. {runapi-0.2.0 → runapi-0.3.0}/runapi/core.py +85 -114
  36. {runapi-0.2.0 → runapi-0.3.0}/runapi/errors.py +50 -19
  37. runapi-0.3.0/runapi/lifecycle.py +77 -0
  38. runapi-0.3.0/runapi/logging.py +98 -0
  39. {runapi-0.2.0 → runapi-0.3.0}/runapi/middleware.py +49 -54
  40. {runapi-0.2.0 → runapi-0.3.0}/runapi/repository.py +5 -4
  41. runapi-0.3.0/runapi/routing.py +122 -0
  42. {runapi-0.2.0 → runapi-0.3.0}/runapi/schemas.py +6 -4
  43. {runapi-0.2.0 → runapi-0.3.0}/runapi/service.py +3 -3
  44. runapi-0.2.0/runapi/cli.py +0 -1226
  45. runapi-0.2.0/runapi/config.py +0 -143
  46. {runapi-0.2.0 → runapi-0.3.0}/LICENSE +0 -0
  47. {runapi-0.2.0 → runapi-0.3.0}/README.md +0 -0
  48. {runapi-0.2.0 → runapi-0.3.0}/examples/basic/README.md +0 -0
  49. {runapi-0.2.0 → runapi-0.3.0}/release-notes/README.md +0 -0
  50. {runapi-0.2.0 → runapi-0.3.0}/runapi/py.typed +0 -0
@@ -107,3 +107,6 @@ credentials.json
107
107
 
108
108
  # Generated by hatch-vcs at build time
109
109
  runapi/_version.py
110
+
111
+ # MkDocs build output
112
+ site/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: runapi
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: A Next.js-inspired file-based routing framework built on FastAPI
5
5
  Project-URL: Homepage, https://github.com/Amanbig/runapi
6
6
  Project-URL: Repository, https://github.com/Amanbig/runapi
@@ -52,6 +52,7 @@ Requires-Dist: aiofiles>=23.2.1
52
52
  Requires-Dist: bcrypt>=4.0.1
53
53
  Requires-Dist: fastapi>=0.115.6
54
54
  Requires-Dist: psutil>=6.0.0
55
+ Requires-Dist: pydantic-settings>=2.2
55
56
  Requires-Dist: pyjwt>=2.10.1
56
57
  Requires-Dist: python-multipart>=0.0.18
57
58
  Requires-Dist: rich>=13.7.0
@@ -72,11 +73,15 @@ Requires-Dist: mkdocs>=1.6; extra == 'docs'
72
73
  Provides-Extra: lint
73
74
  Requires-Dist: mypy>=1.0.0; extra == 'lint'
74
75
  Requires-Dist: ruff>=0.1.0; extra == 'lint'
76
+ Provides-Extra: redis
77
+ Requires-Dist: redis>=5.0; extra == 'redis'
75
78
  Provides-Extra: test
79
+ Requires-Dist: fakeredis>=2.20; extra == 'test'
76
80
  Requires-Dist: httpx>=0.24.0; extra == 'test'
77
81
  Requires-Dist: pytest-asyncio>=0.21.0; extra == 'test'
78
82
  Requires-Dist: pytest-cov>=4.0.0; extra == 'test'
79
83
  Requires-Dist: pytest>=7.0.0; extra == 'test'
84
+ Requires-Dist: redis>=5.0; extra == 'test'
80
85
  Description-Content-Type: text/markdown
81
86
 
82
87
  # Runapi 🚀
@@ -12,6 +12,7 @@ dependencies = [
12
12
  "typer>=0.12.0",
13
13
  "rich>=13.7.0",
14
14
  "bcrypt>=4.0.1",
15
+ "pydantic-settings>=2.2",
15
16
  "PyJWT>=2.10.1",
16
17
  "python-multipart>=0.0.18",
17
18
  "aiofiles>=23.2.1",
@@ -58,6 +59,9 @@ Issues = "https://github.com/Amanbig/runapi/issues"
58
59
  Changelog = "https://github.com/Amanbig/runapi/tree/main/release-notes"
59
60
 
60
61
  [project.optional-dependencies]
62
+ redis = [
63
+ "redis>=5.0",
64
+ ]
61
65
  db = [
62
66
  "sqlalchemy[asyncio]>=2.0",
63
67
  "alembic>=1.13",
@@ -74,6 +78,8 @@ test = [
74
78
  "httpx>=0.24.0",
75
79
  "pytest-asyncio>=0.21.0",
76
80
  "pytest-cov>=4.0.0",
81
+ "redis>=5.0",
82
+ "fakeredis>=2.20",
77
83
  ]
78
84
  docs = [
79
85
  "mkdocs>=1.6",
@@ -125,7 +131,7 @@ known-first-party = ["runapi"]
125
131
 
126
132
  [tool.mypy]
127
133
  python_version = "3.10"
128
- warn_return_any = true
134
+ warn_return_any = false
129
135
  warn_unused_ignores = true
130
136
  disallow_untyped_defs = false
131
137
  ignore_missing_imports = true
@@ -40,6 +40,13 @@ from .auth import (
40
40
  )
41
41
 
42
42
  # Configuration
43
+ from .backends import (
44
+ MemoryRateLimitBackend,
45
+ RateLimitBackend,
46
+ RedisRateLimitBackend,
47
+ RedisTokenBlacklist,
48
+ TokenBlacklist,
49
+ )
43
50
  from .config import RunApiConfig, get_config, load_config
44
51
  from .core import RunApiApp, create_app, create_runapi_app
45
52
 
@@ -47,6 +54,7 @@ from .core import RunApiApp, create_app, create_runapi_app
47
54
  from .errors import (
48
55
  AuthenticationError,
49
56
  AuthorizationError,
57
+ ConfigurationError,
50
58
  ConflictError,
51
59
  DatabaseError,
52
60
  ErrorHandler,
@@ -54,6 +62,7 @@ from .errors import (
54
62
  ExternalServiceError,
55
63
  NotFoundError,
56
64
  RateLimitError,
65
+ RouteLoadError,
57
66
  RunApiException,
58
67
  ServerError,
59
68
  ValidationError,
@@ -76,6 +85,7 @@ from .errors import (
76
85
  )
77
86
 
78
87
  # Middleware
88
+ from .logging import get_request_id
79
89
  from .middleware import (
80
90
  AuthMiddleware,
81
91
  CompressionMiddleware,
@@ -157,6 +167,8 @@ __all__ = [
157
167
  "load_config",
158
168
  # Error handling
159
169
  "RunApiException",
170
+ "ConfigurationError",
171
+ "RouteLoadError",
160
172
  "ValidationError",
161
173
  "AuthenticationError",
162
174
  "AuthorizationError",
@@ -195,6 +207,12 @@ __all__ = [
195
207
  "create_access_token",
196
208
  "create_refresh_token",
197
209
  "verify_token",
210
+ "RateLimitBackend",
211
+ "MemoryRateLimitBackend",
212
+ "RedisRateLimitBackend",
213
+ "TokenBlacklist",
214
+ "RedisTokenBlacklist",
215
+ "get_request_id",
198
216
  "revoke_token",
199
217
  "rotate_refresh_token",
200
218
  "get_current_user",
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.2.0'
22
- __version_tuple__ = version_tuple = (0, 2, 0)
21
+ __version__ = version = '0.3.0'
22
+ __version_tuple__ = version_tuple = (0, 3, 0)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -8,12 +8,13 @@ from typing import Any, Dict, Optional
8
8
  try:
9
9
  import bcrypt
10
10
  except ImportError: # pragma: no cover
11
- bcrypt = None
11
+ bcrypt = None # type: ignore[assignment]
12
12
 
13
13
  import jwt
14
14
  from fastapi import Depends, HTTPException
15
15
  from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
16
16
 
17
+ from .backends import RedisTokenBlacklist, TokenBlacklist, uses_redis
17
18
  from .config import get_config
18
19
 
19
20
 
@@ -23,7 +24,7 @@ class PasswordManager:
23
24
  # bcrypt only considers the first 72 bytes of a password
24
25
  _MAX_BYTES = 72
25
26
 
26
- def __init__(self, schemes: list = None, rounds: int = 12):
27
+ def __init__(self, schemes: Optional[list] = None, rounds: int = 12):
27
28
  if bcrypt is None:
28
29
  raise ImportError(
29
30
  "bcrypt is required for password hashing. Install with: pip install bcrypt"
@@ -55,39 +56,17 @@ class PasswordManager:
55
56
  _RESERVED_CLAIMS = ("exp", "iat", "type", "jti")
56
57
 
57
58
 
58
- class TokenBlacklist:
59
- """In-memory store of revoked token ids (``jti``).
60
-
61
- Subclass and override ``add``/``is_revoked`` to back it with Redis or a database
62
- when running multiple workers.
63
- """
64
-
65
- def __init__(self):
66
- self._revoked: Dict[str, float] = {}
67
-
68
- def add(self, jti: str, expires_at: float) -> None:
69
- self._purge()
70
- self._revoked[jti] = expires_at
71
-
72
- def is_revoked(self, jti: str) -> bool:
73
- return jti in self._revoked
74
-
75
- def _purge(self) -> None:
76
- now = time.time()
77
- for key in [k for k, exp in self._revoked.items() if exp < now]:
78
- del self._revoked[key]
79
-
80
-
81
59
  class JWTManager:
82
60
  """JWT token management utilities using PyJWT."""
83
61
 
84
- def __init__(self, secret_key: str = None, algorithm: str = "HS256"):
62
+ def __init__(self, secret_key: Optional[str] = None, algorithm: str = "HS256"):
85
63
  self.config = get_config()
86
64
  self.secret_key = secret_key or self.config.secret_key
87
65
  self.algorithm = algorithm or self.config.jwt_algorithm
88
66
  self.access_token_expire = self.config.jwt_expiry
89
67
  self.refresh_token_expire = self.config.jwt_refresh_expiry
90
- self.blacklist = TokenBlacklist()
68
+ redis_url = uses_redis(self.config)
69
+ self.blacklist = RedisTokenBlacklist.from_url(redis_url) if redis_url else TokenBlacklist()
91
70
 
92
71
  if self.secret_key == "dev-secret-key-change-in-production":
93
72
  raise ValueError("Change the SECRET_KEY in production!")
@@ -205,7 +184,7 @@ class APIKeyManager:
205
184
  class AuthDependencies:
206
185
  """FastAPI dependency classes for authentication."""
207
186
 
208
- def __init__(self, jwt_manager: JWTManager = None):
187
+ def __init__(self, jwt_manager: Optional[JWTManager] = None):
209
188
  self.jwt_manager = jwt_manager or JWTManager()
210
189
  self.bearer_scheme = HTTPBearer()
211
190
 
@@ -380,7 +359,9 @@ def generate_password(length: int = 12) -> str:
380
359
  class TokenResponse:
381
360
  """Standard token response format."""
382
361
 
383
- def __init__(self, access_token: str, refresh_token: str = None, token_type: str = "bearer"):
362
+ def __init__(
363
+ self, access_token: str, refresh_token: Optional[str] = None, token_type: str = "bearer"
364
+ ):
384
365
  self.access_token = access_token
385
366
  self.refresh_token = refresh_token
386
367
  self.token_type = token_type
@@ -0,0 +1,156 @@
1
+ """Pluggable state backends (in-memory or Redis) for rate limiting and token revocation.
2
+
3
+ In-memory backends are per-process: with several workers each one keeps its own
4
+ counters. Set ``CACHE_BACKEND=redis`` and ``REDIS_URL`` (install ``runapi[redis]``)
5
+ to share state across workers and hosts.
6
+ """
7
+
8
+ import asyncio
9
+ import logging
10
+ import time
11
+ from typing import Any, Dict, List, Optional, Tuple
12
+
13
+ logger = logging.getLogger("runapi")
14
+
15
+
16
+ def _require_redis():
17
+ try:
18
+ import redis # noqa: F401
19
+ except ImportError as exc:
20
+ raise ImportError(
21
+ "The Redis backend needs the 'redis' package. Install with: pip install runapi[redis]"
22
+ ) from exc
23
+
24
+
25
+ # --------------------------------------------------------------------------- #
26
+ # Rate limiting
27
+ # --------------------------------------------------------------------------- #
28
+ class RateLimitBackend:
29
+ """Counts hits per key inside a fixed window."""
30
+
31
+ async def hit(self, key: str, period: int) -> Tuple[int, float]:
32
+ """Record a hit. Returns ``(count_in_window, seconds_until_window_resets)``."""
33
+ raise NotImplementedError
34
+
35
+
36
+ class MemoryRateLimitBackend(RateLimitBackend):
37
+ """Fixed-window counter held in process memory."""
38
+
39
+ def __init__(self):
40
+ self._windows: Dict[str, List[float]] = {} # key -> [count, window_start]
41
+ self._lock = asyncio.Lock()
42
+ self._last_purge = time.time()
43
+
44
+ async def hit(self, key: str, period: int) -> Tuple[int, float]:
45
+ now = time.time()
46
+ async with self._lock:
47
+ if now - self._last_purge > period:
48
+ self._purge(now, period)
49
+ window = self._windows.get(key)
50
+ if window is None or now > window[1] + period:
51
+ window = self._windows[key] = [0, now]
52
+ window[0] += 1
53
+ return int(window[0]), max(window[1] + period - now, 0.0)
54
+
55
+ def _purge(self, now: float, period: int) -> None:
56
+ """Drop expired windows so memory does not grow with every client seen."""
57
+ self._last_purge = now
58
+ for key in [k for k, (_, start) in self._windows.items() if now > start + period]:
59
+ del self._windows[key]
60
+
61
+
62
+ class RedisRateLimitBackend(RateLimitBackend):
63
+ """Fixed-window counter stored in Redis (shared across workers).
64
+
65
+ Fails open: if Redis is unreachable the request is allowed and an error is logged.
66
+ """
67
+
68
+ def __init__(self, client: Any, prefix: str = "runapi:rl:"):
69
+ self.client = client
70
+ self.prefix = prefix
71
+
72
+ @classmethod
73
+ def from_url(cls, url: str, **kwargs: Any) -> "RedisRateLimitBackend":
74
+ _require_redis()
75
+ import redis.asyncio as aioredis
76
+
77
+ return cls(aioredis.from_url(url), **kwargs)
78
+
79
+ async def hit(self, key: str, period: int) -> Tuple[int, float]:
80
+ redis_key = f"{self.prefix}{key}"
81
+ try:
82
+ count = await self.client.incr(redis_key)
83
+ if count == 1:
84
+ await self.client.expire(redis_key, period)
85
+ ttl = await self.client.ttl(redis_key)
86
+ if ttl is None or ttl < 0: # key lost its expiry; restore it
87
+ await self.client.expire(redis_key, period)
88
+ ttl = period
89
+ return int(count), float(ttl)
90
+ except Exception:
91
+ logger.exception("Redis rate limit backend unavailable; allowing request")
92
+ return 0, float(period)
93
+
94
+
95
+ # --------------------------------------------------------------------------- #
96
+ # Token revocation
97
+ # --------------------------------------------------------------------------- #
98
+ class TokenBlacklist:
99
+ """In-memory store of revoked token ids (``jti``).
100
+
101
+ Subclass and override ``add``/``is_revoked`` for other storage.
102
+ """
103
+
104
+ def __init__(self):
105
+ self._revoked: Dict[str, float] = {}
106
+
107
+ def add(self, jti: str, expires_at: float) -> None:
108
+ self._purge()
109
+ self._revoked[jti] = expires_at
110
+
111
+ def is_revoked(self, jti: str) -> bool:
112
+ return jti in self._revoked
113
+
114
+ def _purge(self) -> None:
115
+ now = time.time()
116
+ for key in [k for k, exp in self._revoked.items() if exp < now]:
117
+ del self._revoked[key]
118
+
119
+
120
+ class RedisTokenBlacklist(TokenBlacklist):
121
+ """Revoked token ids stored in Redis with a TTL equal to the token's remaining life.
122
+
123
+ Uses a synchronous client because token verification is synchronous. If Redis is
124
+ unreachable, revocation checks fail closed (the token is treated as revoked).
125
+ """
126
+
127
+ def __init__(self, client: Any, prefix: str = "runapi:revoked:"):
128
+ self.client = client
129
+ self.prefix = prefix
130
+
131
+ @classmethod
132
+ def from_url(cls, url: str, **kwargs: Any) -> "RedisTokenBlacklist":
133
+ _require_redis()
134
+ import redis
135
+
136
+ return cls(redis.Redis.from_url(url), **kwargs)
137
+
138
+ def add(self, jti: str, expires_at: float) -> None:
139
+ ttl = max(int(expires_at - time.time()) + 1, 1)
140
+ self.client.setex(f"{self.prefix}{jti}", ttl, "1")
141
+
142
+ def is_revoked(self, jti: str) -> bool:
143
+ try:
144
+ return bool(self.client.exists(f"{self.prefix}{jti}"))
145
+ except Exception:
146
+ logger.exception("Redis token blacklist unavailable; rejecting token")
147
+ return True
148
+
149
+
150
+ def uses_redis(config: Any) -> Optional[str]:
151
+ """Return the Redis URL when the config selects the Redis backend, else None."""
152
+ if config.cache_backend == "redis":
153
+ if not config.redis_url:
154
+ raise ValueError("CACHE_BACKEND=redis requires REDIS_URL")
155
+ return config.redis_url
156
+ return None
@@ -0,0 +1,53 @@
1
+ """The ``runapi`` command-line interface.
2
+
3
+ Layout:
4
+ _app.py shared Typer ``app`` and ``console``
5
+ _templates.py renderer for the files the CLI generates
6
+ commands/ one module per group of commands (importing registers them)
7
+ templates/ the generated files themselves, as plain ``*.tmpl`` files
8
+ """
9
+
10
+ import typer
11
+
12
+ from .. import __version__
13
+ from . import commands # noqa: F401
14
+ from ._app import app, console
15
+ from .commands import db, generate, inspect, project, server # noqa: F401 (registers commands)
16
+
17
+
18
+ def _version_callback(value: bool):
19
+ if value:
20
+ typer.echo(f"runapi {__version__}")
21
+ raise typer.Exit()
22
+
23
+
24
+ @app.callback()
25
+ def _root(
26
+ version: bool = typer.Option(
27
+ False,
28
+ "--version",
29
+ "-V",
30
+ callback=_version_callback,
31
+ is_eager=True,
32
+ help="Show the runapi version and exit.",
33
+ ),
34
+ ):
35
+ """RunApi - Next.js-inspired Python Backend Framework."""
36
+
37
+
38
+ def main():
39
+ """Main entry point for CLI."""
40
+ from ..errors import ConfigurationError
41
+
42
+ try:
43
+ app()
44
+ except ConfigurationError as exc:
45
+ console.print(f"[red]❌ {exc}[/red]")
46
+ raise SystemExit(1) from None
47
+
48
+
49
+ __all__ = ["app", "console", "main"]
50
+
51
+
52
+ if __name__ == "__main__":
53
+ main()
@@ -0,0 +1,7 @@
1
+ """The shared Typer app and console used by every command module."""
2
+
3
+ import typer
4
+ from rich.console import Console
5
+
6
+ app = typer.Typer(name="runapi", help="RunApi - Next.js-inspired Python Backend Framework")
7
+ console = Console()
@@ -0,0 +1,28 @@
1
+ """Tiny template renderer for the files the CLI generates.
2
+
3
+ Templates live in ``runapi/cli/templates`` as plain files so they can be read, diffed and
4
+ syntax-checked like any other code. Placeholders look like ``@@name@@``.
5
+ """
6
+
7
+ import re
8
+ from importlib import resources
9
+ from typing import Dict
10
+
11
+ _PLACEHOLDER = re.compile(r"@@(\w+)@@")
12
+
13
+
14
+ def render(template: str, **context: str) -> str:
15
+ """Render ``templates/<template>.tmpl`` replacing every ``@@key@@`` from ``context``."""
16
+ text = (resources.files("runapi.cli") / "templates" / f"{template}.tmpl").read_text(
17
+ encoding="utf-8"
18
+ )
19
+ missing = set(_PLACEHOLDER.findall(text)) - set(context)
20
+ if missing:
21
+ raise KeyError(f"Template {template!r} needs values for: {', '.join(sorted(missing))}")
22
+ values: Dict[str, str] = {key: str(value) for key, value in context.items()}
23
+ return _PLACEHOLDER.sub(lambda match: values[match.group(1)], text)
24
+
25
+
26
+ def class_name_for(name: str) -> str:
27
+ """Convert ``my-thing`` / ``my_thing`` to ``MyThing``."""
28
+ return "".join(word.capitalize() for word in name.replace("-", "_").split("_"))
@@ -0,0 +1 @@
1
+ """CLI command modules. Importing them registers their commands on the app."""
@@ -0,0 +1,69 @@
1
+ """`runapi build` and the `runapi db` migration commands."""
2
+
3
+ import subprocess
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ import typer
8
+
9
+ from .._app import app, console
10
+
11
+
12
+ @app.command()
13
+ def build(
14
+ tag: str = typer.Option("runapi-app", "--tag", "-t", help="Docker image tag"),
15
+ path: str = typer.Argument(".", help="Project directory"),
16
+ ):
17
+ """Build a Docker image for the project (requires Docker and a Dockerfile)."""
18
+ project = Path(path)
19
+ if not (project / "Dockerfile").exists():
20
+ console.print("[red]❌ No Dockerfile found. Create one with: runapi init <name> --docker")
21
+ raise typer.Exit(code=1)
22
+ console.print(f"🐳 [bold blue]Building image {tag}[/bold blue]")
23
+ try:
24
+ result = subprocess.run(["docker", "build", "-t", tag, str(project)])
25
+ except FileNotFoundError:
26
+ console.print("[red]❌ Docker is not installed or not on PATH")
27
+ raise typer.Exit(code=1) from None
28
+ if result.returncode != 0:
29
+ raise typer.Exit(code=result.returncode)
30
+ console.print(f"✅ [green]Built {tag}[/green] (run: docker run -p 8000:8000 {tag})")
31
+
32
+
33
+ db_app = typer.Typer(help="Database migrations (Alembic). Install with: pip install runapi\\[db]")
34
+ app.add_typer(db_app, name="db")
35
+
36
+
37
+ def _alembic(*args: str):
38
+ try:
39
+ import alembic # noqa: F401
40
+ except ImportError:
41
+ console.print("[red]❌ Alembic is not installed. Run: pip install runapi\\[db]")
42
+ raise typer.Exit(code=1) from None
43
+ result = subprocess.run([sys.executable, "-m", "alembic", *args])
44
+ if result.returncode != 0:
45
+ raise typer.Exit(code=result.returncode)
46
+
47
+
48
+ @db_app.command("init")
49
+ def db_init(directory: str = typer.Option("migrations", help="Migrations directory")):
50
+ """Initialise Alembic migrations (async-ready template)."""
51
+ _alembic("init", "-t", "async", directory)
52
+
53
+
54
+ @db_app.command("migrate")
55
+ def db_migrate(message: str = typer.Option(..., "--message", "-m", help="Migration message")):
56
+ """Autogenerate a new migration from model changes."""
57
+ _alembic("revision", "--autogenerate", "-m", message)
58
+
59
+
60
+ @db_app.command("upgrade")
61
+ def db_upgrade(revision: str = typer.Argument("head")):
62
+ """Apply migrations up to a revision (default: head)."""
63
+ _alembic("upgrade", revision)
64
+
65
+
66
+ @db_app.command("downgrade")
67
+ def db_downgrade(revision: str = typer.Argument("-1")):
68
+ """Revert migrations (default: one step)."""
69
+ _alembic("downgrade", revision)