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/__init__.py +174 -0
- runapi/auth.py +359 -0
- runapi/cli.py +576 -0
- runapi/config.py +141 -0
- runapi/core.py +219 -0
- runapi/errors.py +338 -0
- runapi/middleware.py +383 -0
- runapi-0.1.0.dist-info/METADATA +797 -0
- runapi-0.1.0.dist-info/RECORD +12 -0
- runapi-0.1.0.dist-info/WHEEL +4 -0
- runapi-0.1.0.dist-info/entry_points.txt +2 -0
- runapi-0.1.0.dist-info/licenses/LICENSE +21 -0
runapi/config.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import List, Optional, Dict, Any
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class RunApiConfig:
|
|
7
|
+
"""Configuration management for RunApi framework."""
|
|
8
|
+
|
|
9
|
+
def __init__(self, env_file: Optional[str] = None):
|
|
10
|
+
self.env_file = env_file or ".env"
|
|
11
|
+
self._load_env_file()
|
|
12
|
+
|
|
13
|
+
# Core settings
|
|
14
|
+
self.debug: bool = self._get_bool("DEBUG", True)
|
|
15
|
+
self.host: str = self._get_str("HOST", "127.0.0.1")
|
|
16
|
+
self.port: int = self._get_int("PORT", 8000)
|
|
17
|
+
self.reload: bool = self._get_bool("RELOAD", True)
|
|
18
|
+
|
|
19
|
+
# Security settings
|
|
20
|
+
self.secret_key: str = self._get_str("SECRET_KEY", "dev-secret-key-change-in-production")
|
|
21
|
+
self.allowed_hosts: List[str] = self._get_list("ALLOWED_HOSTS", ["*"])
|
|
22
|
+
|
|
23
|
+
# CORS settings
|
|
24
|
+
self.cors_origins: List[str] = self._get_list("CORS_ORIGINS", ["*"])
|
|
25
|
+
self.cors_credentials: bool = self._get_bool("CORS_CREDENTIALS", True)
|
|
26
|
+
self.cors_methods: List[str] = self._get_list("CORS_METHODS", ["*"])
|
|
27
|
+
self.cors_headers: List[str] = self._get_list("CORS_HEADERS", ["*"])
|
|
28
|
+
|
|
29
|
+
# Database settings
|
|
30
|
+
self.database_url: Optional[str] = self._get_str("DATABASE_URL")
|
|
31
|
+
self.database_echo: bool = self._get_bool("DATABASE_ECHO", False)
|
|
32
|
+
|
|
33
|
+
# Cache settings
|
|
34
|
+
self.cache_backend: str = self._get_str("CACHE_BACKEND", "memory")
|
|
35
|
+
self.redis_url: Optional[str] = self._get_str("REDIS_URL")
|
|
36
|
+
self.cache_ttl: int = self._get_int("CACHE_TTL", 300) # 5 minutes default
|
|
37
|
+
|
|
38
|
+
# Rate limiting
|
|
39
|
+
self.rate_limit_enabled: bool = self._get_bool("RATE_LIMIT_ENABLED", False)
|
|
40
|
+
self.rate_limit_calls: int = self._get_int("RATE_LIMIT_CALLS", 100)
|
|
41
|
+
self.rate_limit_period: int = self._get_int("RATE_LIMIT_PERIOD", 60) # 1 minute
|
|
42
|
+
|
|
43
|
+
# Logging
|
|
44
|
+
self.log_level: str = self._get_str("LOG_LEVEL", "INFO")
|
|
45
|
+
self.log_format: str = self._get_str("LOG_FORMAT", "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
|
46
|
+
|
|
47
|
+
# Static files
|
|
48
|
+
self.static_files_enabled: bool = self._get_bool("STATIC_FILES_ENABLED", True)
|
|
49
|
+
self.static_files_path: str = self._get_str("STATIC_FILES_PATH", "static")
|
|
50
|
+
self.static_files_url: str = self._get_str("STATIC_FILES_URL", "/static")
|
|
51
|
+
|
|
52
|
+
# Upload settings
|
|
53
|
+
self.max_upload_size: int = self._get_int("MAX_UPLOAD_SIZE", 10 * 1024 * 1024) # 10MB
|
|
54
|
+
self.upload_path: str = self._get_str("UPLOAD_PATH", "uploads")
|
|
55
|
+
|
|
56
|
+
# JWT settings
|
|
57
|
+
self.jwt_algorithm: str = self._get_str("JWT_ALGORITHM", "HS256")
|
|
58
|
+
self.jwt_expiry: int = self._get_int("JWT_EXPIRY", 3600) # 1 hour
|
|
59
|
+
self.jwt_refresh_expiry: int = self._get_int("JWT_REFRESH_EXPIRY", 86400) # 24 hours
|
|
60
|
+
|
|
61
|
+
# Custom settings
|
|
62
|
+
self.custom: Dict[str, Any] = {}
|
|
63
|
+
|
|
64
|
+
def _load_env_file(self):
|
|
65
|
+
"""Load environment variables from .env file if it exists."""
|
|
66
|
+
env_path = Path(self.env_file)
|
|
67
|
+
if env_path.exists():
|
|
68
|
+
with open(env_path, 'r', encoding='utf-8') as f:
|
|
69
|
+
for line in f:
|
|
70
|
+
line = line.strip()
|
|
71
|
+
if line and not line.startswith('#') and '=' in line:
|
|
72
|
+
key, value = line.split('=', 1)
|
|
73
|
+
key = key.strip()
|
|
74
|
+
value = value.strip().strip('"').strip("'")
|
|
75
|
+
os.environ[key] = value
|
|
76
|
+
|
|
77
|
+
def _get_str(self, key: str, default: Optional[str] = None) -> Optional[str]:
|
|
78
|
+
"""Get string value from environment."""
|
|
79
|
+
return os.getenv(key, default)
|
|
80
|
+
|
|
81
|
+
def _get_bool(self, key: str, default: bool = False) -> bool:
|
|
82
|
+
"""Get boolean value from environment."""
|
|
83
|
+
value = os.getenv(key, str(default)).lower()
|
|
84
|
+
return value in ('true', '1', 'yes', 'on')
|
|
85
|
+
|
|
86
|
+
def _get_int(self, key: str, default: int = 0) -> int:
|
|
87
|
+
"""Get integer value from environment."""
|
|
88
|
+
try:
|
|
89
|
+
return int(os.getenv(key, str(default)))
|
|
90
|
+
except ValueError:
|
|
91
|
+
return default
|
|
92
|
+
|
|
93
|
+
def _get_float(self, key: str, default: float = 0.0) -> float:
|
|
94
|
+
"""Get float value from environment."""
|
|
95
|
+
try:
|
|
96
|
+
return float(os.getenv(key, str(default)))
|
|
97
|
+
except ValueError:
|
|
98
|
+
return default
|
|
99
|
+
|
|
100
|
+
def _get_list(self, key: str, default: List[str] = None) -> List[str]:
|
|
101
|
+
"""Get list value from environment (comma-separated)."""
|
|
102
|
+
if default is None:
|
|
103
|
+
default = []
|
|
104
|
+
|
|
105
|
+
value = os.getenv(key)
|
|
106
|
+
if not value:
|
|
107
|
+
return default
|
|
108
|
+
|
|
109
|
+
return [item.strip() for item in value.split(',') if item.strip()]
|
|
110
|
+
|
|
111
|
+
def get(self, key: str, default: Any = None) -> Any:
|
|
112
|
+
"""Get custom configuration value."""
|
|
113
|
+
return self.custom.get(key, default)
|
|
114
|
+
|
|
115
|
+
def set(self, key: str, value: Any) -> None:
|
|
116
|
+
"""Set custom configuration value."""
|
|
117
|
+
self.custom[key] = value
|
|
118
|
+
|
|
119
|
+
def is_development(self) -> bool:
|
|
120
|
+
"""Check if running in development mode."""
|
|
121
|
+
return self.debug
|
|
122
|
+
|
|
123
|
+
def is_production(self) -> bool:
|
|
124
|
+
"""Check if running in production mode."""
|
|
125
|
+
return not self.debug
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# Global configuration instance
|
|
129
|
+
config = RunApiConfig()
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def get_config() -> RunApiConfig:
|
|
133
|
+
"""Get the global configuration instance."""
|
|
134
|
+
return config
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def load_config(env_file: Optional[str] = None) -> RunApiConfig:
|
|
138
|
+
"""Load configuration with optional custom env file."""
|
|
139
|
+
global config
|
|
140
|
+
config = RunApiConfig(env_file)
|
|
141
|
+
return config
|
runapi/core.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
# runapi/core.py
|
|
2
|
+
from fastapi import FastAPI, APIRouter
|
|
3
|
+
from fastapi.staticfiles import StaticFiles
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import importlib.util
|
|
6
|
+
import logging
|
|
7
|
+
from typing import List, Optional, Type, Dict, Any
|
|
8
|
+
|
|
9
|
+
from .config import get_config, RunApiConfig
|
|
10
|
+
from .middleware import (
|
|
11
|
+
CORSMiddleware,
|
|
12
|
+
RequestLoggingMiddleware,
|
|
13
|
+
RateLimitMiddleware,
|
|
14
|
+
AuthMiddleware,
|
|
15
|
+
SecurityHeadersMiddleware,
|
|
16
|
+
CompressionMiddleware,
|
|
17
|
+
RunApiMiddleware
|
|
18
|
+
)
|
|
19
|
+
from .errors import setup_error_handlers
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class RunApiApp:
|
|
23
|
+
"""Enhanced RunApi application class with configuration and middleware support."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, config: Optional[RunApiConfig] = None, **fastapi_kwargs):
|
|
26
|
+
self.config = config or get_config()
|
|
27
|
+
self.app = self._create_fastapi_app(**fastapi_kwargs)
|
|
28
|
+
self.middleware_stack: List[Type[RunApiMiddleware]] = []
|
|
29
|
+
|
|
30
|
+
# Setup logging
|
|
31
|
+
self._setup_logging()
|
|
32
|
+
|
|
33
|
+
# Setup default middleware
|
|
34
|
+
self._setup_default_middleware()
|
|
35
|
+
|
|
36
|
+
# Setup error handlers
|
|
37
|
+
self._setup_error_handlers()
|
|
38
|
+
|
|
39
|
+
# Load routes
|
|
40
|
+
self._load_routes()
|
|
41
|
+
|
|
42
|
+
# Setup static files
|
|
43
|
+
self._setup_static_files()
|
|
44
|
+
|
|
45
|
+
def _create_fastapi_app(self, **kwargs) -> FastAPI:
|
|
46
|
+
"""Create FastAPI application with configuration."""
|
|
47
|
+
# Merge config with kwargs
|
|
48
|
+
app_kwargs = {
|
|
49
|
+
"debug": self.config.debug,
|
|
50
|
+
"title": kwargs.get("title", "RunApi API"),
|
|
51
|
+
"description": kwargs.get("description", "API built with RunApi framework"),
|
|
52
|
+
"version": kwargs.get("version", "1.0.0"),
|
|
53
|
+
}
|
|
54
|
+
app_kwargs.update(kwargs)
|
|
55
|
+
|
|
56
|
+
return FastAPI(**app_kwargs)
|
|
57
|
+
|
|
58
|
+
def _setup_logging(self):
|
|
59
|
+
"""Setup logging configuration."""
|
|
60
|
+
logging.basicConfig(
|
|
61
|
+
level=getattr(logging, self.config.log_level.upper()),
|
|
62
|
+
format=self.config.log_format
|
|
63
|
+
)
|
|
64
|
+
self.logger = logging.getLogger("runapi")
|
|
65
|
+
|
|
66
|
+
def _setup_default_middleware(self):
|
|
67
|
+
"""Setup default middleware based on configuration."""
|
|
68
|
+
# CORS middleware
|
|
69
|
+
if self.config.cors_origins:
|
|
70
|
+
from fastapi.middleware.cors import CORSMiddleware as FastAPICORSMiddleware
|
|
71
|
+
self.app.add_middleware(
|
|
72
|
+
FastAPICORSMiddleware,
|
|
73
|
+
allow_origins=self.config.cors_origins,
|
|
74
|
+
allow_credentials=self.config.cors_credentials,
|
|
75
|
+
allow_methods=self.config.cors_methods,
|
|
76
|
+
allow_headers=self.config.cors_headers
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
# Rate limiting middleware
|
|
80
|
+
if self.config.rate_limit_enabled:
|
|
81
|
+
self.app.add_middleware(
|
|
82
|
+
RateLimitMiddleware,
|
|
83
|
+
calls=self.config.rate_limit_calls,
|
|
84
|
+
period=self.config.rate_limit_period
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
# Security headers middleware
|
|
88
|
+
self.app.add_middleware(SecurityHeadersMiddleware)
|
|
89
|
+
|
|
90
|
+
# Request logging middleware
|
|
91
|
+
if self.config.debug:
|
|
92
|
+
self.app.add_middleware(RequestLoggingMiddleware, logger=self.logger)
|
|
93
|
+
|
|
94
|
+
# Compression middleware
|
|
95
|
+
self.app.add_middleware(CompressionMiddleware)
|
|
96
|
+
|
|
97
|
+
def _setup_error_handlers(self):
|
|
98
|
+
"""Setup error handlers for the application."""
|
|
99
|
+
setup_error_handlers(self.app, self.logger, self.config.debug)
|
|
100
|
+
|
|
101
|
+
def _setup_static_files(self):
|
|
102
|
+
"""Setup static file serving."""
|
|
103
|
+
if self.config.static_files_enabled:
|
|
104
|
+
static_path = Path(self.config.static_files_path)
|
|
105
|
+
if static_path.exists():
|
|
106
|
+
self.app.mount(
|
|
107
|
+
self.config.static_files_url,
|
|
108
|
+
StaticFiles(directory=str(static_path)),
|
|
109
|
+
name="static"
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
def _load_routes(self):
|
|
113
|
+
"""Load routes from project's routes/ folder."""
|
|
114
|
+
routes_path = Path("routes")
|
|
115
|
+
if routes_path.exists():
|
|
116
|
+
self._load_routes_recursive(routes_path)
|
|
117
|
+
|
|
118
|
+
def _load_routes_recursive(self, routes_dir: Path, prefix: str = ""):
|
|
119
|
+
"""Recursively load routes from directory structure."""
|
|
120
|
+
router = APIRouter(prefix=prefix)
|
|
121
|
+
|
|
122
|
+
for item in routes_dir.iterdir():
|
|
123
|
+
if item.is_dir():
|
|
124
|
+
# Recurse into subfolders (e.g., routes/api/users)
|
|
125
|
+
new_prefix = f"{prefix}/{item.name}"
|
|
126
|
+
self._load_routes_recursive(item, new_prefix)
|
|
127
|
+
elif item.suffix == ".py" and item.name != "__init__.py":
|
|
128
|
+
self._load_route_file(item, prefix)
|
|
129
|
+
|
|
130
|
+
def _load_route_file(self, route_file: Path, prefix: str = ""):
|
|
131
|
+
"""Load a single route file."""
|
|
132
|
+
try:
|
|
133
|
+
route_name = route_file.stem
|
|
134
|
+
module_name = f"routes.{prefix.replace('/', '.')}.{route_name}".strip(".")
|
|
135
|
+
|
|
136
|
+
spec = importlib.util.spec_from_file_location(module_name, route_file)
|
|
137
|
+
module = importlib.util.module_from_spec(spec)
|
|
138
|
+
spec.loader.exec_module(module)
|
|
139
|
+
|
|
140
|
+
# Extract router or create one
|
|
141
|
+
route_router = getattr(module, "router", APIRouter())
|
|
142
|
+
|
|
143
|
+
# Map HTTP methods to functions
|
|
144
|
+
for method in ["get", "post", "put", "delete", "patch", "head", "options", "trace"]:
|
|
145
|
+
if hasattr(module, method):
|
|
146
|
+
path = self._get_route_path(route_name)
|
|
147
|
+
getattr(route_router, method)(path)(getattr(module, method))
|
|
148
|
+
|
|
149
|
+
# Include the router with proper prefix
|
|
150
|
+
final_prefix = prefix if prefix else ""
|
|
151
|
+
self.app.include_router(route_router, prefix=final_prefix)
|
|
152
|
+
|
|
153
|
+
self.logger.debug(f"Loaded route: {route_file} with prefix: {final_prefix}")
|
|
154
|
+
|
|
155
|
+
except Exception as e:
|
|
156
|
+
self.logger.error(f"Failed to load route {route_file}: {e}")
|
|
157
|
+
|
|
158
|
+
def _get_route_path(self, route_name: str) -> str:
|
|
159
|
+
"""Convert route name to FastAPI path."""
|
|
160
|
+
if route_name == "index":
|
|
161
|
+
return "/"
|
|
162
|
+
elif route_name.startswith("[") and route_name.endswith("]"):
|
|
163
|
+
# Dynamic route: [id] -> {id}
|
|
164
|
+
param_name = route_name[1:-1]
|
|
165
|
+
return f"/{{{param_name}}}"
|
|
166
|
+
elif route_name.startswith("[...") and route_name.endswith("]"):
|
|
167
|
+
# Catch-all route: [...slug] -> {slug:path}
|
|
168
|
+
param_name = route_name[4:-1]
|
|
169
|
+
return f"/{{{param_name}:path}}"
|
|
170
|
+
else:
|
|
171
|
+
return f"/{route_name}"
|
|
172
|
+
|
|
173
|
+
def add_middleware(self, middleware_class: Type[RunApiMiddleware], **kwargs):
|
|
174
|
+
"""Add custom middleware to the application."""
|
|
175
|
+
self.app.add_middleware(middleware_class, **kwargs)
|
|
176
|
+
self.middleware_stack.append(middleware_class)
|
|
177
|
+
self.logger.debug(f"Added middleware: {middleware_class.__name__}")
|
|
178
|
+
|
|
179
|
+
def add_auth_middleware(self, protected_paths: List[str] = None, excluded_paths: List[str] = None):
|
|
180
|
+
"""Add JWT authentication middleware."""
|
|
181
|
+
if not self.config.secret_key or self.config.secret_key == "dev-secret-key-change-in-production":
|
|
182
|
+
self.logger.warning("Using default secret key. Change SECRET_KEY in production!")
|
|
183
|
+
|
|
184
|
+
self.add_middleware(
|
|
185
|
+
AuthMiddleware,
|
|
186
|
+
secret_key=self.config.secret_key,
|
|
187
|
+
protected_paths=protected_paths,
|
|
188
|
+
excluded_paths=excluded_paths
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
def get_app(self) -> FastAPI:
|
|
192
|
+
"""Get the underlying FastAPI application."""
|
|
193
|
+
return self.app
|
|
194
|
+
|
|
195
|
+
def run(self, host: str = None, port: int = None, **uvicorn_kwargs):
|
|
196
|
+
"""Run the application with uvicorn."""
|
|
197
|
+
import uvicorn
|
|
198
|
+
|
|
199
|
+
run_kwargs = {
|
|
200
|
+
"host": host or self.config.host,
|
|
201
|
+
"port": port or self.config.port,
|
|
202
|
+
"reload": self.config.reload,
|
|
203
|
+
"log_level": self.config.log_level.lower(),
|
|
204
|
+
**uvicorn_kwargs
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
self.logger.info(f"Starting RunApi server on {run_kwargs['host']}:{run_kwargs['port']}")
|
|
208
|
+
uvicorn.run(self.app, **run_kwargs)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def create_app(config: Optional[RunApiConfig] = None, **kwargs) -> FastAPI:
|
|
212
|
+
"""Create a RunApi FastAPI application."""
|
|
213
|
+
runapi_app = RunApiApp(config=config, **kwargs)
|
|
214
|
+
return runapi_app.get_app()
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def create_runapi_app(config: Optional[RunApiConfig] = None, **kwargs) -> RunApiApp:
|
|
218
|
+
"""Create a RunApi application instance."""
|
|
219
|
+
return RunApiApp(config=config, **kwargs)
|
runapi/errors.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Error handling system for RunApi framework
|
|
3
|
+
"""
|
|
4
|
+
import traceback
|
|
5
|
+
from typing import Dict, Any, Optional, Union
|
|
6
|
+
from fastapi import HTTPException, Request
|
|
7
|
+
from fastapi.responses import JSONResponse
|
|
8
|
+
from fastapi.exception_handlers import http_exception_handler
|
|
9
|
+
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
10
|
+
import logging
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class RunApiException(Exception):
|
|
14
|
+
"""Base exception class for RunApi framework."""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
message: str,
|
|
19
|
+
status_code: int = 500,
|
|
20
|
+
details: Optional[Dict[str, Any]] = None,
|
|
21
|
+
error_code: Optional[str] = None
|
|
22
|
+
):
|
|
23
|
+
self.message = message
|
|
24
|
+
self.status_code = status_code
|
|
25
|
+
self.details = details or {}
|
|
26
|
+
self.error_code = error_code or self.__class__.__name__
|
|
27
|
+
super().__init__(self.message)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ValidationError(RunApiException):
|
|
31
|
+
"""Raised when request validation fails."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, message: str = "Validation failed", details: Dict[str, Any] = None):
|
|
34
|
+
super().__init__(message, 400, details, "VALIDATION_ERROR")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class AuthenticationError(RunApiException):
|
|
38
|
+
"""Raised when authentication fails."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, message: str = "Authentication required", details: Dict[str, Any] = None):
|
|
41
|
+
super().__init__(message, 401, details, "AUTHENTICATION_ERROR")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class AuthorizationError(RunApiException):
|
|
45
|
+
"""Raised when authorization fails."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, message: str = "Insufficient permissions", details: Dict[str, Any] = None):
|
|
48
|
+
super().__init__(message, 403, details, "AUTHORIZATION_ERROR")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class NotFoundError(RunApiException):
|
|
52
|
+
"""Raised when a resource is not found."""
|
|
53
|
+
|
|
54
|
+
def __init__(self, message: str = "Resource not found", details: Dict[str, Any] = None):
|
|
55
|
+
super().__init__(message, 404, details, "NOT_FOUND_ERROR")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class ConflictError(RunApiException):
|
|
59
|
+
"""Raised when there's a conflict with the current state."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, message: str = "Conflict with current state", details: Dict[str, Any] = None):
|
|
62
|
+
super().__init__(message, 409, details, "CONFLICT_ERROR")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class RateLimitError(RunApiException):
|
|
66
|
+
"""Raised when rate limit is exceeded."""
|
|
67
|
+
|
|
68
|
+
def __init__(self, message: str = "Rate limit exceeded", details: Dict[str, Any] = None):
|
|
69
|
+
super().__init__(message, 429, details, "RATE_LIMIT_ERROR")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class ServerError(RunApiException):
|
|
73
|
+
"""Raised when an internal server error occurs."""
|
|
74
|
+
|
|
75
|
+
def __init__(self, message: str = "Internal server error", details: Dict[str, Any] = None):
|
|
76
|
+
super().__init__(message, 500, details, "SERVER_ERROR")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class DatabaseError(RunApiException):
|
|
80
|
+
"""Raised when database operations fail."""
|
|
81
|
+
|
|
82
|
+
def __init__(self, message: str = "Database operation failed", details: Dict[str, Any] = None):
|
|
83
|
+
super().__init__(message, 500, details, "DATABASE_ERROR")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class ExternalServiceError(RunApiException):
|
|
87
|
+
"""Raised when external service calls fail."""
|
|
88
|
+
|
|
89
|
+
def __init__(self, message: str = "External service error", details: Dict[str, Any] = None):
|
|
90
|
+
super().__init__(message, 502, details, "EXTERNAL_SERVICE_ERROR")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class ErrorResponse:
|
|
94
|
+
"""Standard error response format."""
|
|
95
|
+
|
|
96
|
+
def __init__(
|
|
97
|
+
self,
|
|
98
|
+
message: str,
|
|
99
|
+
status_code: int = 500,
|
|
100
|
+
error_code: str = "UNKNOWN_ERROR",
|
|
101
|
+
details: Optional[Dict[str, Any]] = None,
|
|
102
|
+
request_id: Optional[str] = None
|
|
103
|
+
):
|
|
104
|
+
self.message = message
|
|
105
|
+
self.status_code = status_code
|
|
106
|
+
self.error_code = error_code
|
|
107
|
+
self.details = details or {}
|
|
108
|
+
self.request_id = request_id
|
|
109
|
+
|
|
110
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
111
|
+
"""Convert error response to dictionary."""
|
|
112
|
+
response = {
|
|
113
|
+
"error": {
|
|
114
|
+
"code": self.error_code,
|
|
115
|
+
"message": self.message,
|
|
116
|
+
"status_code": self.status_code
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if self.details:
|
|
121
|
+
response["error"]["details"] = self.details
|
|
122
|
+
|
|
123
|
+
if self.request_id:
|
|
124
|
+
response["error"]["request_id"] = self.request_id
|
|
125
|
+
|
|
126
|
+
return response
|
|
127
|
+
|
|
128
|
+
def to_json_response(self) -> JSONResponse:
|
|
129
|
+
"""Convert to FastAPI JSONResponse."""
|
|
130
|
+
return JSONResponse(
|
|
131
|
+
status_code=self.status_code,
|
|
132
|
+
content=self.to_dict()
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class ErrorHandler:
|
|
137
|
+
"""Error handler with logging and formatting."""
|
|
138
|
+
|
|
139
|
+
def __init__(self, logger: Optional[logging.Logger] = None, debug: bool = False):
|
|
140
|
+
self.logger = logger or logging.getLogger(__name__)
|
|
141
|
+
self.debug = debug
|
|
142
|
+
|
|
143
|
+
def handle_runapi_exception(self, request: Request, exc: RunApiException) -> JSONResponse:
|
|
144
|
+
"""Handle RunApi custom exceptions."""
|
|
145
|
+
self.logger.warning(
|
|
146
|
+
f"RunApi exception: {exc.error_code} - {exc.message}",
|
|
147
|
+
extra={"status_code": exc.status_code, "details": exc.details}
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
error_response = ErrorResponse(
|
|
151
|
+
message=exc.message,
|
|
152
|
+
status_code=exc.status_code,
|
|
153
|
+
error_code=exc.error_code,
|
|
154
|
+
details=exc.details,
|
|
155
|
+
request_id=getattr(request.state, "request_id", None)
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
return error_response.to_json_response()
|
|
159
|
+
|
|
160
|
+
def handle_http_exception(self, request: Request, exc: HTTPException) -> JSONResponse:
|
|
161
|
+
"""Handle FastAPI HTTP exceptions."""
|
|
162
|
+
self.logger.warning(f"HTTP exception: {exc.status_code} - {exc.detail}")
|
|
163
|
+
|
|
164
|
+
error_response = ErrorResponse(
|
|
165
|
+
message=str(exc.detail),
|
|
166
|
+
status_code=exc.status_code,
|
|
167
|
+
error_code="HTTP_ERROR",
|
|
168
|
+
request_id=getattr(request.state, "request_id", None)
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
return error_response.to_json_response()
|
|
172
|
+
|
|
173
|
+
def handle_validation_exception(self, request: Request, exc: Exception) -> JSONResponse:
|
|
174
|
+
"""Handle Pydantic validation exceptions."""
|
|
175
|
+
self.logger.warning(f"Validation exception: {str(exc)}")
|
|
176
|
+
|
|
177
|
+
details = {}
|
|
178
|
+
if hasattr(exc, "errors"):
|
|
179
|
+
details = {"validation_errors": exc.errors()}
|
|
180
|
+
|
|
181
|
+
error_response = ErrorResponse(
|
|
182
|
+
message="Request validation failed",
|
|
183
|
+
status_code=422,
|
|
184
|
+
error_code="VALIDATION_ERROR",
|
|
185
|
+
details=details,
|
|
186
|
+
request_id=getattr(request.state, "request_id", None)
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
return error_response.to_json_response()
|
|
190
|
+
|
|
191
|
+
def handle_generic_exception(self, request: Request, exc: Exception) -> JSONResponse:
|
|
192
|
+
"""Handle generic exceptions."""
|
|
193
|
+
self.logger.error(
|
|
194
|
+
f"Unhandled exception: {type(exc).__name__} - {str(exc)}",
|
|
195
|
+
exc_info=True
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
details = {}
|
|
199
|
+
if self.debug:
|
|
200
|
+
details = {
|
|
201
|
+
"exception_type": type(exc).__name__,
|
|
202
|
+
"exception_message": str(exc),
|
|
203
|
+
"traceback": traceback.format_exc().split('\n')
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
error_response = ErrorResponse(
|
|
207
|
+
message="An unexpected error occurred" if not self.debug else str(exc),
|
|
208
|
+
status_code=500,
|
|
209
|
+
error_code="INTERNAL_ERROR",
|
|
210
|
+
details=details,
|
|
211
|
+
request_id=getattr(request.state, "request_id", None)
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
return error_response.to_json_response()
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
# Global error handler instance
|
|
218
|
+
error_handler = ErrorHandler()
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def setup_error_handlers(app, logger: Optional[logging.Logger] = None, debug: bool = False):
|
|
222
|
+
"""Setup error handlers for a FastAPI application."""
|
|
223
|
+
handler = ErrorHandler(logger, debug)
|
|
224
|
+
|
|
225
|
+
@app.exception_handler(RunApiException)
|
|
226
|
+
async def runapi_exception_handler(request: Request, exc: RunApiException):
|
|
227
|
+
return handler.handle_runapi_exception(request, exc)
|
|
228
|
+
|
|
229
|
+
@app.exception_handler(HTTPException)
|
|
230
|
+
async def http_exception_handler(request: Request, exc: HTTPException):
|
|
231
|
+
return handler.handle_http_exception(request, exc)
|
|
232
|
+
|
|
233
|
+
@app.exception_handler(StarletteHTTPException)
|
|
234
|
+
async def starlette_http_exception_handler(request: Request, exc: StarletteHTTPException):
|
|
235
|
+
return handler.handle_http_exception(request, HTTPException(status_code=exc.status_code, detail=exc.detail))
|
|
236
|
+
|
|
237
|
+
# Handle validation errors from Pydantic
|
|
238
|
+
try:
|
|
239
|
+
from pydantic import ValidationError as PydanticValidationError
|
|
240
|
+
|
|
241
|
+
@app.exception_handler(PydanticValidationError)
|
|
242
|
+
async def pydantic_validation_exception_handler(request: Request, exc: PydanticValidationError):
|
|
243
|
+
return handler.handle_validation_exception(request, exc)
|
|
244
|
+
except ImportError:
|
|
245
|
+
pass
|
|
246
|
+
|
|
247
|
+
# Handle generic exceptions
|
|
248
|
+
@app.exception_handler(Exception)
|
|
249
|
+
async def generic_exception_handler(request: Request, exc: Exception):
|
|
250
|
+
return handler.handle_generic_exception(request, exc)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# Convenience functions
|
|
254
|
+
def raise_validation_error(message: str, details: Dict[str, Any] = None):
|
|
255
|
+
"""Raise a validation error."""
|
|
256
|
+
raise ValidationError(message, details)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def raise_auth_error(message: str = "Authentication required"):
|
|
260
|
+
"""Raise an authentication error."""
|
|
261
|
+
raise AuthenticationError(message)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def raise_permission_error(message: str = "Insufficient permissions"):
|
|
265
|
+
"""Raise an authorization error."""
|
|
266
|
+
raise AuthorizationError(message)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def raise_not_found(message: str = "Resource not found"):
|
|
270
|
+
"""Raise a not found error."""
|
|
271
|
+
raise NotFoundError(message)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def raise_conflict(message: str = "Conflict with current state"):
|
|
275
|
+
"""Raise a conflict error."""
|
|
276
|
+
raise ConflictError(message)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def raise_server_error(message: str = "Internal server error"):
|
|
280
|
+
"""Raise a server error."""
|
|
281
|
+
raise ServerError(message)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def create_error_response(
|
|
285
|
+
message: str,
|
|
286
|
+
status_code: int = 500,
|
|
287
|
+
error_code: str = "ERROR",
|
|
288
|
+
details: Dict[str, Any] = None
|
|
289
|
+
) -> JSONResponse:
|
|
290
|
+
"""Create a standard error response."""
|
|
291
|
+
error_response = ErrorResponse(
|
|
292
|
+
message=message,
|
|
293
|
+
status_code=status_code,
|
|
294
|
+
error_code=error_code,
|
|
295
|
+
details=details
|
|
296
|
+
)
|
|
297
|
+
return error_response.to_json_response()
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
# HTTP status code helpers
|
|
301
|
+
def bad_request(message: str = "Bad request", details: Dict[str, Any] = None) -> JSONResponse:
|
|
302
|
+
"""Return a 400 Bad Request response."""
|
|
303
|
+
return create_error_response(message, 400, "BAD_REQUEST", details)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def unauthorized(message: str = "Unauthorized", details: Dict[str, Any] = None) -> JSONResponse:
|
|
307
|
+
"""Return a 401 Unauthorized response."""
|
|
308
|
+
return create_error_response(message, 401, "UNAUTHORIZED", details)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def forbidden(message: str = "Forbidden", details: Dict[str, Any] = None) -> JSONResponse:
|
|
312
|
+
"""Return a 403 Forbidden response."""
|
|
313
|
+
return create_error_response(message, 403, "FORBIDDEN", details)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def not_found(message: str = "Not found", details: Dict[str, Any] = None) -> JSONResponse:
|
|
317
|
+
"""Return a 404 Not Found response."""
|
|
318
|
+
return create_error_response(message, 404, "NOT_FOUND", details)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def conflict(message: str = "Conflict", details: Dict[str, Any] = None) -> JSONResponse:
|
|
322
|
+
"""Return a 409 Conflict response."""
|
|
323
|
+
return create_error_response(message, 409, "CONFLICT", details)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def unprocessable_entity(message: str = "Unprocessable Entity", details: Dict[str, Any] = None) -> JSONResponse:
|
|
327
|
+
"""Return a 422 Unprocessable Entity response."""
|
|
328
|
+
return create_error_response(message, 422, "UNPROCESSABLE_ENTITY", details)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def rate_limited(message: str = "Rate limit exceeded", details: Dict[str, Any] = None) -> JSONResponse:
|
|
332
|
+
"""Return a 429 Too Many Requests response."""
|
|
333
|
+
return create_error_response(message, 429, "RATE_LIMITED", details)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def internal_error(message: str = "Internal server error", details: Dict[str, Any] = None) -> JSONResponse:
|
|
337
|
+
"""Return a 500 Internal Server Error response."""
|
|
338
|
+
return create_error_response(message, 500, "INTERNAL_ERROR", details)
|