Cython routing added

This commit is contained in:
Илья Глазунов
2026-01-31 02:44:50 +03:00
parent fe541778f1
commit eeeccd57da
10 changed files with 1106 additions and 63 deletions
+11 -53
View File
@@ -1,7 +1,6 @@
import mimetypes
import re
from pathlib import Path
from typing import Any, Dict, Optional, Pattern
from typing import Any, Dict
from urllib.parse import urlparse
import httpx
@@ -10,60 +9,19 @@ from starlette.responses import FileResponse, PlainTextResponse, Response
from .logging_utils import get_logger
try:
from pyserve._routing import FastRouteMatch, FastRouter, fast_match # type: ignore
CYTHON_ROUTING_AVAILABLE = True
except ImportError:
from pyserve._routing_py import FastRouteMatch, FastRouter, fast_match
CYTHON_ROUTING_AVAILABLE = False
logger = get_logger(__name__)
class RouteMatch:
def __init__(self, config: Dict[str, Any], params: Optional[Dict[str, str]] = None):
self.config = config
self.params = params or {}
class Router:
def __init__(self, static_dir: str = "./static"):
self.static_dir = Path(static_dir)
self.routes: Dict[Pattern, Dict[str, Any]] = {}
self.exact_routes: Dict[str, Dict[str, Any]] = {}
self.default_route: Optional[Dict[str, Any]] = None
def add_route(self, pattern: str, config: Dict[str, Any]) -> None:
if pattern.startswith("="):
exact_path = pattern[1:]
self.exact_routes[exact_path] = config
logger.debug(f"Added exact route: {exact_path}")
return
if pattern == "__default__":
self.default_route = config
logger.debug("Added default route")
return
if pattern.startswith("~"):
case_insensitive = pattern.startswith("~*")
regex_pattern = pattern[2:] if case_insensitive else pattern[1:]
flags = re.IGNORECASE if case_insensitive else 0
try:
compiled_pattern = re.compile(regex_pattern, flags)
self.routes[compiled_pattern] = config
logger.debug(f"Added regex route: {pattern}")
except re.error as e:
logger.error(f"Regex compilation error {pattern}: {e}")
def match(self, path: str) -> Optional[RouteMatch]:
if path in self.exact_routes:
return RouteMatch(self.exact_routes[path])
for pattern, config in self.routes.items():
match = pattern.search(path)
if match:
params = match.groupdict()
return RouteMatch(config, params)
if self.default_route:
return RouteMatch(self.default_route)
return None
# Aliases for backward compatibility
RouteMatch = FastRouteMatch
Router = FastRouter
class RequestHandler: