Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Nov 13, 2023
1 parent 8ac0ea6 commit 84add1d
Show file tree
Hide file tree
Showing 10 changed files with 24 additions and 28 deletions.
10 changes: 8 additions & 2 deletions integration_tests/base_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,14 @@ def jsonws_connect():

@websocket_di.on("connect")
async def di_message_connect(global_dependencies, router_dependencies):
return global_dependencies["GLOBAL_DEPENDENCY"] + " "+ router_dependencies["ROUTER_DEPENDENCY"]
return global_dependencies["GLOBAL_DEPENDENCY"] + " " + router_dependencies["ROUTER_DEPENDENCY"]


@websocket_di.on("message")
async def di_message():
return ""


@websocket_di.on("close")
async def di_message_close():
return ""
Expand Down Expand Up @@ -210,9 +212,11 @@ def sync_middlewares_401():

app.inject(RouterDependency="Router Dependency")


@app.get("/")
async def hello_world(request):
return f"Hello, world!"
return "Hello, world!"


@app.get("/sync/str")
def sync_str_get():
Expand Down Expand Up @@ -788,10 +792,12 @@ async def async_without_decorator():
app.inject_global(GLOBAL_DEPENDENCY=GLOBAL_DEPENDENCY)
app.inject(ROUTER_DEPENDENCY=ROUTER_DEPENDENCY)


@app.get("/sync/global_di")
def sync_global_di(request, router_dependencies, global_dependencies):
return global_dependencies["GLOBAL_DEPENDENCY"]


@app.get("/sync/router_di")
def sync_router_di(request, router_dependencies):
return router_dependencies["ROUTER_DEPENDENCY"]
Expand Down
1 change: 1 addition & 0 deletions integration_tests/subroutes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

__all__ = ["sub_router", "websocket", "di_subrouter"]


@websocket.on("connect")
async def connect(ws):
return "Hello world, from ws"
Expand Down
1 change: 1 addition & 0 deletions integration_tests/subroutes/di_subrouter.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
def sync_subrouter_route_dependency(request, router_dependencies):
return router_dependencies["ROUTER_DEPENDENCY"]


@di_subrouter.get("/subrouter_global_di")
def sync_subrouter_global_dependency(request, global_dependencies):
return global_dependencies["GLOBAL_DEPENDENCY"]
1 change: 1 addition & 0 deletions integration_tests/test_dependency_injection.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ def test_router_dependency_injection(benchmark):
assert r.status_code == 200
assert r.text == "ROUTER DEPENDENCY"


@pytest.mark.benchmark
def test_subrouter_global_dependency_injection(benchmark):
r = get("/di_subrouter/subrouter_global_di")
Expand Down
2 changes: 1 addition & 1 deletion integration_tests/test_web_sockets.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ def test_web_socket_json(session):
assert resp["resp"] == "*chika* *chika* Slim Shady."
assert resp["msg"] == msg


def test_websocket_di(session):
"""
Not using this as the benchmark test since this involves JSON marshalling/unmarshalling
Expand All @@ -58,4 +59,3 @@ def test_websocket_di(session):

ws = create_connection(f"{BASE_URL}/web_socket_di")
assert ws.recv() == msg

10 changes: 1 addition & 9 deletions robyn/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,7 @@ def __init__(
self.exception_handler: Optional[Callable] = None
self.authentication_handler: Optional[AuthenticationHandler] = None

def add_route(
self,
route_type: Union[HttpMethod, str],
endpoint: str,
handler: Callable,
is_const: bool = False,
auth_required: bool = False
):
def add_route(self, route_type: Union[HttpMethod, str], endpoint: str, handler: Callable, is_const: bool = False, auth_required: bool = False):
"""
Connect a URI to a handler
Expand Down Expand Up @@ -110,7 +103,6 @@ def add_route(
}
route_type = http_methods[route_type]


add_route_response = self.router.add_route(
route_type=route_type,
endpoint=endpoint,
Expand Down
9 changes: 5 additions & 4 deletions robyn/dependency_injection.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
""" This is Robyn's dependency injection file.
"""


class DependencyMap:
def __init__(self):
#'request' and 'response' mappings are needed for when constructing deps_to_pass in router.py
Expand Down Expand Up @@ -64,7 +65,7 @@ def merge_dependencies(self, target_router):
target_router.dependencies.get_global_dependencies()[dep_key] = self.get_global_dependencies()[dep_key]

def get_dependency_map(self, router) -> dict:
return {
"global_dependencies": self.get_global_dependencies(),
"router_dependencies": self.get_router_dependencies(router),
}
return {
"global_dependencies": self.get_global_dependencies(),
"router_dependencies": self.get_router_dependencies(router),
}
3 changes: 3 additions & 0 deletions robyn/robyn.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ class MiddlewareType(Enum):
BEFORE_REQUEST: str
AFTER_REQUEST: str
"""

BEFORE_REQUEST: str
AFTER_REQUEST: str

Expand All @@ -47,6 +48,7 @@ class HttpMethod(Enum):
TRACE: str
CONNECT: str
"""

GET: str
POST: str
PUT: str
Expand All @@ -69,6 +71,7 @@ class FunctionInfo:
args (dict): The arguments of the function
kwargs (dict): The keyword arguments of the function
"""

handler: Callable
is_async: bool
number_of_params: int
Expand Down
12 changes: 2 additions & 10 deletions robyn/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from functools import wraps
from inspect import signature
from types import CoroutineType
from typing import Any, Callable, Dict, List, NamedTuple, Union, Optional
from typing import Callable, Dict, List, NamedTuple, Union, Optional
from robyn.authentication import AuthenticationHandler, AuthenticationNotConfiguredError
from robyn.dependency_injection import DependencyMap

Expand Down Expand Up @@ -135,16 +135,13 @@ def inner_handler(*args, **kwargs):
# these are the arguments
params = dict(inspect.signature(handler).parameters)



new_injected_dependencies = {}
for dependency in injected_dependencies:
if dependency in params:
new_injected_dependencies[dependency] = injected_dependencies[dependency]
else:
_logger.warning(f"Dependency {dependency} is not used in the handler {handler.__name__}")


if iscoroutinefunction(handler):
function = FunctionInfo(async_inner_handler, True, number_of_params, params, new_injected_dependencies)
self.routes.append(Route(route_type, endpoint, function, is_const))
Expand All @@ -170,12 +167,10 @@ def set_authentication_handler(self, authentication_handler: AuthenticationHandl
self.authentication_handler = authentication_handler

def add_route(self, middleware_type: MiddlewareType, endpoint: str, handler: Callable, injected_dependencies: dict) -> Callable:

# add a docstring here
params = dict(inspect.signature(handler).parameters)
number_of_params = len(params)


new_injected_dependencies = {}
for dependency in injected_dependencies:
if dependency in params:
Expand All @@ -185,8 +180,6 @@ def add_route(self, middleware_type: MiddlewareType, endpoint: str, handler: Cal

print("This is new injected dependencies", new_injected_dependencies)



function = FunctionInfo(handler, iscoroutinefunction(handler), number_of_params, params, new_injected_dependencies)
self.route_middlewares.append(RouteMiddleware(middleware_type, endpoint, function))
return handler
Expand All @@ -207,15 +200,14 @@ def inner_handler(request: Request, *args):
if identity is None:
return self.authentication_handler.unauthorized_response
request.identity = identity

return request

self.add_route(MiddlewareType.BEFORE_REQUEST, endpoint, inner_handler, injected_dependencies)
return inner_handler

return decorator


# These inner functions are basically a wrapper around the closure(decorator) being returned.
# They take a handler, convert it into a closure and return the arguments.
# Arguments are returned as they could be modified by the middlewares.
Expand Down
3 changes: 1 addition & 2 deletions robyn/ws.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

import asyncio
from inspect import signature
import inspect
from typing import TYPE_CHECKING, Callable
from robyn.argument_parser import Config
Expand All @@ -16,6 +15,7 @@

_logger = logging.getLogger(__name__)


class WebSocket:
# should this be websocket router?
"""This is the python wrapper for the web socket that will be used here."""
Expand All @@ -35,7 +35,6 @@ def inner(handler):
params = dict(inspect.signature(handler).parameters)
num_params = len(params)
is_async = asyncio.iscoroutinefunction(handler)


injected_dependencies = self.dependencies.get_dependency_map(self)

Expand Down

0 comments on commit 84add1d

Please sign in to comment.