From 995d0d9738251d56f74fe07f57a4fb8f88882d96 Mon Sep 17 00:00:00 2001 From: Leonid Vinogradov Date: Thu, 15 Feb 2024 14:06:59 +0300 Subject: [PATCH] review fix --- frontik/dependency_manager.py | 57 +++++++++++++++++++++++------------ frontik/handler.py | 15 ++++++--- 2 files changed, 48 insertions(+), 24 deletions(-) diff --git a/frontik/dependency_manager.py b/frontik/dependency_manager.py index 74322515c..f9037176d 100644 --- a/frontik/dependency_manager.py +++ b/frontik/dependency_manager.py @@ -1,10 +1,38 @@ -from contextvars import ContextVar from typing import Any, Callable +from fastapi import APIRouter as FastApiRouter from fastapi import Request from fastapi.dependencies.utils import solve_dependencies -current_handler: ContextVar = ContextVar('current_handler') + +class APIRouter(FastApiRouter): + def get(self, **kwargs) -> Callable: # type: ignore + return super().get('', **kwargs) + + def post(self, **kwargs) -> Callable: # type: ignore + return super().post('', **kwargs) + + def put(self, **kwargs) -> Callable: # type: ignore + return super().put('', **kwargs) + + def delete(self, **kwargs) -> Callable: # type: ignore + return super().delete('', **kwargs) + + def api_route(self, *args, **kwargs): + decorator = super().api_route(*args, **kwargs) + + def frontik_decorator(func): + decorator(func) + func._route = self.routes[-1] + route_method = func._route.methods # type: ignore + + if func.__name__ in ('get_page', 'post_page', 'put_page', 'delete_page') and route_method != { + func.__name__.split('_')[0].upper(), + }: + raise RuntimeError(f'Wrong router type func={func.__name__} method={route_method}') + return func + + return frontik_decorator async def execute_page_method_with_dependencies(handler: Any, get_page_method: Callable) -> Any: @@ -15,22 +43,13 @@ async def execute_page_method_with_dependencies(handler: Any, get_page_method: C 'handler': handler, }) - route = next((rr for rr in handler.router.routes if rr.name == get_page_method.__name__ and rr.path == '/'), None) - - if route is None: - route = next( - (rr for rr in handler.router.routes if rr.name == get_page_method.__name__ and rr.path == '/base'), - None, - ) - - if route is not None: - token = current_handler.set(handler) - solved_result = await solve_dependencies( - request=request, - dependant=route.dependant, - body=None, - dependency_overrides_provider=None, - ) - current_handler.reset(token) + route = get_page_method._route # type: ignore + + await solve_dependencies( + request=request, + dependant=route.dependant, + body=None, + dependency_overrides_provider=None, + ) return await get_page_method() diff --git a/frontik/handler.py b/frontik/handler.py index ddbf59f06..677643e31 100644 --- a/frontik/handler.py +++ b/frontik/handler.py @@ -12,7 +12,7 @@ import tornado.httputil import tornado.web -from fastapi import APIRouter +from fastapi import Request # noqa from http_client.request_response import USER_AGENT_HEADER, FailFastError, RequestBuilder, RequestResult from pydantic import BaseModel, ValidationError from tornado.ioloop import IOLoop @@ -26,7 +26,7 @@ from frontik import media_types, request_context from frontik.auth import DEBUG_AUTH_HEADER_NAME from frontik.debug import DEBUG_HEADER_NAME, DebugMode -from frontik.dependency_manager import current_handler, execute_page_method_with_dependencies +from frontik.dependency_manager import APIRouter, execute_page_method_with_dependencies from frontik.futures import AbortAsyncGroup, AsyncGroup from frontik.http_status import ALLOWED_STATUSES, CLIENT_CLOSED_REQUEST from frontik.json_builder import FrontikJsonDecodeError, json_decode @@ -76,6 +76,7 @@ def __init__(self, *args: object) -> None: OUTER_TIMEOUT_MS_HEADER = 'X-Outer-Timeout-Ms' handler_logger = logging.getLogger('handler') +router = APIRouter() def _fail_fast_policy(fail_fast: bool, waited: bool, host: str, path: str) -> bool: @@ -91,7 +92,6 @@ def _fail_fast_policy(fail_fast: bool, waited: bool, host: str, path: str) -> bo class PageHandler(RequestHandler): - router = APIRouter() returned_value_handlers: ReturnedValueHandlers = [] def __init__(self, application: FrontikApplication, request: HTTPServerRequest, **kwargs: Any) -> None: @@ -380,18 +380,22 @@ async def _execute_page(self, page_handler_method: Callable[[], Coroutine[Any, A if render_result is not None: self.write(render_result) + @router.get() async def get_page(self): """This method can be implemented in the subclass""" self.__return_405() + @router.post() async def post_page(self): """This method can be implemented in the subclass""" self.__return_405() + @router.put() async def put_page(self): """This method can be implemented in the subclass""" self.__return_405() + @router.delete() async def delete_page(self): """This method can be implemented in the subclass""" self.__return_405() @@ -955,9 +959,10 @@ class ErrorHandler(PageHandler, tornado.web.ErrorHandler): class RedirectHandler(PageHandler, tornado.web.RedirectHandler): + @router.get() def get_page(self): tornado.web.RedirectHandler.get(self) -def get_current_handler() -> PageHandler: - return current_handler.get() +def get_current_handler(request: Request) -> PageHandler: + return request['handler']