|
| 1 | +""" |
| 2 | +Compatibility layer for FastAPI -> Starlette migration. |
| 3 | +Provides FastAPI-like API on top of Starlette. |
| 4 | +""" |
| 5 | +from starlette.routing import Router |
| 6 | +from starlette.requests import Request |
| 7 | +from starlette.responses import HTMLResponse, RedirectResponse, JSONResponse, Response |
| 8 | +from starlette.status import HTTP_200_OK, HTTP_201_CREATED, HTTP_400_BAD_REQUEST, HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN, HTTP_404_NOT_FOUND, HTTP_422_UNPROCESSABLE_ENTITY, HTTP_500_INTERNAL_SERVER_ERROR |
| 9 | +from typing import Any, Callable, Optional |
| 10 | +from functools import wraps |
| 11 | +import inspect |
| 12 | + |
| 13 | + |
| 14 | +# Export Starlette classes as FastAPI-compatible names |
| 15 | +__all__ = [ |
| 16 | + 'APIRouter', |
| 17 | + 'Request', |
| 18 | + 'HTMLResponse', |
| 19 | + 'RedirectResponse', |
| 20 | + 'JSONResponse', |
| 21 | + 'Response', |
| 22 | + 'HTTPException', |
| 23 | + 'status', |
| 24 | + 'Depends', |
| 25 | + 'OAuth2PasswordBearer', |
| 26 | +] |
| 27 | + |
| 28 | + |
| 29 | +class APIRouter(Router): |
| 30 | + """ |
| 31 | + FastAPI-compatible router based on Starlette Router. |
| 32 | + """ |
| 33 | + def __init__(self, prefix: str = "", tags: Optional[list] = None, **kwargs): |
| 34 | + super().__init__(**kwargs) |
| 35 | + self.prefix = prefix |
| 36 | + self.tags = tags or [] |
| 37 | + self._routes = [] |
| 38 | + |
| 39 | + def include_router(self, router: 'APIRouter', prefix: str = "", tags: Optional[list] = None, include_in_schema: bool = True): |
| 40 | + """ |
| 41 | + Include another router into this router. |
| 42 | + """ |
| 43 | + full_prefix = self.prefix + prefix |
| 44 | + if tags: |
| 45 | + combined_tags = self.tags + tags |
| 46 | + else: |
| 47 | + combined_tags = self.tags |
| 48 | + |
| 49 | + # Mount the router with the combined prefix |
| 50 | + if full_prefix: |
| 51 | + # Create a new router with the prefix |
| 52 | + prefixed_router = Router() |
| 53 | + prefixed_router.mount(full_prefix, router) |
| 54 | + self.mount("", prefixed_router) |
| 55 | + else: |
| 56 | + self.mount("", router) |
| 57 | + |
| 58 | + def get(self, path: str, **kwargs): |
| 59 | + """Decorator for GET routes.""" |
| 60 | + def decorator(func: Callable): |
| 61 | + return self.add_route(path, func, methods=["GET"], **kwargs) |
| 62 | + return decorator |
| 63 | + |
| 64 | + def post(self, path: str, **kwargs): |
| 65 | + """Decorator for POST routes.""" |
| 66 | + def decorator(func: Callable): |
| 67 | + return self.add_route(path, func, methods=["POST"], **kwargs) |
| 68 | + return decorator |
| 69 | + |
| 70 | + def put(self, path: str, **kwargs): |
| 71 | + """Decorator for PUT routes.""" |
| 72 | + def decorator(func: Callable): |
| 73 | + return self.add_route(path, func, methods=["PUT"], **kwargs) |
| 74 | + return decorator |
| 75 | + |
| 76 | + def delete(self, path: str, **kwargs): |
| 77 | + """Decorator for DELETE routes.""" |
| 78 | + def decorator(func: Callable): |
| 79 | + return self.add_route(path, func, methods=["DELETE"], **kwargs) |
| 80 | + return decorator |
| 81 | + |
| 82 | + def patch(self, path: str, **kwargs): |
| 83 | + """Decorator for PATCH routes.""" |
| 84 | + def decorator(func: Callable): |
| 85 | + return self.add_route(path, func, methods=["PATCH"], **kwargs) |
| 86 | + return decorator |
| 87 | + |
| 88 | + |
| 89 | +class HTTPException(Exception): |
| 90 | + """HTTP exception for error responses.""" |
| 91 | + def __init__(self, status_code: int, detail: Any = None, headers: Optional[dict] = None): |
| 92 | + self.status_code = status_code |
| 93 | + self.detail = detail |
| 94 | + self.headers = headers |
| 95 | + |
| 96 | + |
| 97 | +# Status codes module |
| 98 | +class status: |
| 99 | + HTTP_200_OK = HTTP_200_OK |
| 100 | + HTTP_201_CREATED = HTTP_201_CREATED |
| 101 | + HTTP_400_BAD_REQUEST = HTTP_400_BAD_REQUEST |
| 102 | + HTTP_401_UNAUTHORIZED = HTTP_401_UNAUTHORIZED |
| 103 | + HTTP_403_FORBIDDEN = HTTP_403_FORBIDDEN |
| 104 | + HTTP_404_NOT_FOUND = HTTP_404_NOT_FOUND |
| 105 | + HTTP_422_UNPROCESSABLE_ENTITY = HTTP_422_UNPROCESSABLE_ENTITY |
| 106 | + HTTP_500_INTERNAL_SERVER_ERROR = HTTP_500_INTERNAL_SERVER_ERROR |
| 107 | + |
| 108 | + |
| 109 | +# Dependency injection system |
| 110 | +class Depends: |
| 111 | + """ |
| 112 | + Dependency injection system compatible with FastAPI's Depends. |
| 113 | + """ |
| 114 | + def __init__(self, dependency: Callable): |
| 115 | + self.dependency = dependency |
| 116 | + |
| 117 | + async def __call__(self, request: Request): |
| 118 | + """Resolve the dependency.""" |
| 119 | + if inspect.iscoroutinefunction(self.dependency): |
| 120 | + return await self.dependency(request) |
| 121 | + else: |
| 122 | + return self.dependency(request) |
| 123 | + |
| 124 | + |
| 125 | +# OAuth2PasswordBearer replacement |
| 126 | +class OAuth2PasswordBearer: |
| 127 | + """ |
| 128 | + OAuth2 password bearer token extractor. |
| 129 | + """ |
| 130 | + def __init__(self, tokenUrl: str, scheme_name: Optional[str] = None): |
| 131 | + self.tokenUrl = tokenUrl |
| 132 | + self.scheme_name = scheme_name or "OAuth2" |
| 133 | + |
| 134 | + async def __call__(self, request: Request) -> str: |
| 135 | + """Extract token from Authorization header.""" |
| 136 | + authorization = request.headers.get("Authorization") |
| 137 | + if not authorization: |
| 138 | + raise HTTPException( |
| 139 | + status_code=status.HTTP_403_FORBIDDEN, |
| 140 | + detail="Not authenticated" |
| 141 | + ) |
| 142 | + scheme, token = authorization.split(" ", 1) |
| 143 | + if scheme.lower() != "bearer": |
| 144 | + raise HTTPException( |
| 145 | + status_code=status.HTTP_403_FORBIDDEN, |
| 146 | + detail="Invalid authentication scheme" |
| 147 | + ) |
| 148 | + return token |
0 commit comments