-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathrouting.py
More file actions
234 lines (186 loc) · 7.54 KB
/
routing.py
File metadata and controls
234 lines (186 loc) · 7.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
"""
TurboAPI Route Registration System
FastAPI-compatible decorators with revolutionary performance
"""
import inspect
import re
from collections.abc import Callable
from dataclasses import dataclass
from enum import Enum
from typing import Any
from .version_check import CHECK_MARK
class HTTPMethod(Enum):
"""HTTP methods supported by TurboAPI."""
GET = "GET"
POST = "POST"
PUT = "PUT"
DELETE = "DELETE"
PATCH = "PATCH"
HEAD = "HEAD"
OPTIONS = "OPTIONS"
@dataclass
class PathParameter:
"""Path parameter definition."""
name: str
type: type
default: Any = None
required: bool = True
@dataclass
class RouteDefinition:
"""Complete route definition."""
path: str
method: HTTPMethod
handler: Callable
path_params: list[PathParameter]
query_params: dict[str, type]
request_model: type | None = None
response_model: type | None = None
tags: list[str] = None
summary: str | None = None
description: str | None = None
class RouteRegistry:
"""Registry for all routes in the application."""
def __init__(self):
self.routes: list[RouteDefinition] = []
self.path_patterns: dict[str, re.Pattern] = {}
def register_route(self, route: RouteDefinition) -> None:
"""Register a new route."""
self.routes.append(route)
# Compile path pattern for fast matching
pattern = self._compile_path_pattern(route.path)
self.path_patterns[route.path] = pattern
print(f"{CHECK_MARK} Registered route: {route.method.value} {route.path}")
def _compile_path_pattern(self, path: str) -> re.Pattern:
"""Compile path with parameters into regex pattern."""
# Convert FastAPI-style {param} to regex groups
pattern = path
# Find all path parameters
param_matches = re.findall(r"\{([^}]+)\}", path)
for param in param_matches:
# Replace {param} with named regex group
pattern = pattern.replace(f"{{{param}}}", f"(?P<{param}>[^/]+)")
# Ensure exact match
pattern = f"^{pattern}$"
return re.compile(pattern)
def match_route(self, method: str, path: str) -> tuple | None:
"""Match incoming request to registered route."""
for route in self.routes:
if route.method.value != method:
continue
pattern = self.path_patterns.get(route.path)
if not pattern:
continue
match = pattern.match(path)
if match:
# Extract path parameters
path_params = match.groupdict()
return route, path_params
return None
def get_routes(self) -> list[RouteDefinition]:
"""Get all registered routes."""
return self.routes.copy()
class Router:
"""FastAPI-compatible router with decorators."""
def __init__(self, prefix: str = "", tags: list[str] = None, dependencies: list = None):
self.prefix = prefix
self.tags = tags or []
self.dependencies = dependencies or []
self.registry = RouteRegistry()
def _create_route_decorator(self, method: HTTPMethod):
"""Create a route decorator for the given HTTP method."""
def decorator(
path: str,
*,
response_model: type | None = None,
tags: list[str] = None,
summary: str | None = None,
description: str | None = None,
**kwargs,
):
def wrapper(func: Callable) -> Callable:
# Analyze function signature
sig = inspect.signature(func)
path_params = []
query_params = {}
request_model = None
for param_name, param in sig.parameters.items():
if param_name in path:
# Path parameter
path_param = PathParameter(
name=param_name,
type=param.annotation
if param.annotation != inspect.Parameter.empty
else str,
default=param.default
if param.default != inspect.Parameter.empty
else None,
required=param.default == inspect.Parameter.empty,
)
path_params.append(path_param)
elif param.annotation != inspect.Parameter.empty:
# Check if it's a request model (class type)
if inspect.isclass(param.annotation):
request_model = param.annotation
else:
# Query parameter
query_params[param_name] = param.annotation
# Create route definition
full_path = self.prefix + path
route = RouteDefinition(
path=full_path,
method=method,
handler=func,
path_params=path_params,
query_params=query_params,
request_model=request_model,
response_model=response_model,
tags=(tags or []) + self.tags,
summary=summary,
description=description,
)
# Register the route
self.registry.register_route(route)
# Return the original function (for direct calling)
return func
return wrapper
return decorator
def get(self, path: str, **kwargs):
"""GET route decorator."""
return self._create_route_decorator(HTTPMethod.GET)(path, **kwargs)
def post(self, path: str, **kwargs):
"""POST route decorator."""
return self._create_route_decorator(HTTPMethod.POST)(path, **kwargs)
def put(self, path: str, **kwargs):
"""PUT route decorator."""
return self._create_route_decorator(HTTPMethod.PUT)(path, **kwargs)
def delete(self, path: str, **kwargs):
"""DELETE route decorator."""
return self._create_route_decorator(HTTPMethod.DELETE)(path, **kwargs)
def patch(self, path: str, **kwargs):
"""PATCH route decorator."""
return self._create_route_decorator(HTTPMethod.PATCH)(path, **kwargs)
def head(self, path: str, **kwargs):
"""HEAD route decorator."""
return self._create_route_decorator(HTTPMethod.HEAD)(path, **kwargs)
def options(self, path: str, **kwargs):
"""OPTIONS route decorator."""
return self._create_route_decorator(HTTPMethod.OPTIONS)(path, **kwargs)
def include_router(self, router: Router, prefix: str = "", tags: list[str] = None):
"""Include another router's routes."""
for route in router.registry.get_routes():
# Create new route with updated prefix and tags
new_route = RouteDefinition(
path=prefix + route.path,
method=route.method,
handler=route.handler,
path_params=route.path_params,
query_params=route.query_params,
request_model=route.request_model,
response_model=route.response_model,
tags=(tags or []) + (route.tags or []),
summary=route.summary,
description=route.description,
)
self.registry.register_route(new_route)
# Global router instance for the main app
APIRouter = Router