Skip to content

Commit

Permalink
review fix
Browse files Browse the repository at this point in the history
  • Loading branch information
712u3 committed Feb 15, 2024
1 parent b060e1e commit 995d0d9
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 24 deletions.
57 changes: 38 additions & 19 deletions frontik/dependency_manager.py
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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()
15 changes: 10 additions & 5 deletions frontik/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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']

0 comments on commit 995d0d9

Please sign in to comment.