Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Custom Response objects. #165

Merged
merged 6 commits into from
Mar 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions integration_tests/base_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,18 @@ async def hello(request):
global callCount
callCount += 1
message = "Called " + str(callCount) + " times"
print(message)
return jsonify(request)
print(message, request)
return {"status_code": "200", "body": "hello", "type": "text"}


@app.get('/404')
def return_404():
return {"status_code": "404", "body": "hello", "type": "text"}


@app.post('/404')
def return_404_post():
return {"status_code": "404", "body": "hello", "type": "text"}


@app.before_request("/")
Expand Down
13 changes: 13 additions & 0 deletions integration_tests/test_status_code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import requests

BASE_URL = "http://127.0.0.1:5000"


def test_404_status_code(session):
res = requests.get(f"{BASE_URL}/404")
assert res.status_code == 404


def test_404_post_request_status_code(session):
r = requests.post(f"{BASE_URL}/404")
assert r.status_code == 404
114 changes: 21 additions & 93 deletions robyn/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from .processpool import spawn_process
from .log_colors import Colors
from .ws import WS
from .router import Router, MiddlewareRouter, WebSocketRouter

# 3rd party imports and exports
from multiprocess import Process
Expand All @@ -32,15 +33,14 @@ def __init__(self, file_object):
self.dev = self.parser.is_dev()
self.processes = self.parser.num_processes()
self.workers = self.parser.workers()
self.routes = []
self.router = Router()
self.middleware_router = MiddlewareRouter()
self.web_socket_router = WebSocketRouter()
self.headers = []
self.routes = []
self.middlewares = []
self.web_sockets = {}
self.directories = []
self.event_handlers = {}

def add_route(self, route_type, endpoint, handler):
def _add_route(self, route_type, endpoint, handler):
"""
[This is base handler for all the decorators]

Expand All @@ -51,94 +51,23 @@ def add_route(self, route_type, endpoint, handler):

""" We will add the status code here only
"""
number_of_params = len(signature(handler).parameters)
self.routes.append(
(
route_type,
endpoint,
handler,
asyncio.iscoroutinefunction(handler),
number_of_params,
)
)

def add_middleware_route(self, route_type, endpoint, handler):
"""
[This is base handler for the middleware decorator]

:param route_type [str]: [??]
:param endpoint [str]: [endpoint for the route added]
:param handler [function]: [represents the sync or async function passed as a handler for the route]
"""

""" We will add the status code here only
"""
number_of_params = len(signature(handler).parameters)
self.middlewares.append(
(
route_type,
endpoint,
handler,
asyncio.iscoroutinefunction(handler),
number_of_params,
)
)
self.router.add_route(route_type, endpoint, handler)

def before_request(self, endpoint):
"""
[The @app.before_request decorator to add a get route]

:param endpoint [str]: [endpoint to server the route]
"""

# This inner function is basically a wrapper arround the closure(decorator)
# being returned.
# It takes in a handler and converts it in into a closure
# and returns the arguments.
# Arguments are returned as they could be modified by the middlewares.
def inner(handler):
async def async_inner_handler(*args):
await handler(args)
return args

def inner_handler(*args):
handler(*args)
return args

if asyncio.iscoroutinefunction(handler):
self.add_middleware_route("BEFORE_REQUEST", endpoint, async_inner_handler)
else:
self.add_middleware_route("BEFORE_REQUEST", endpoint, inner_handler)

return inner
return self.middleware_router.add_before_request(endpoint)

def after_request(self, endpoint):
"""
[The @app.after_request decorator to add a get route]

:param endpoint [str]: [endpoint to server the route]
"""

# This inner function is basically a wrapper arround the closure(decorator)
# being returned.
# It takes in a handler and converts it in into a closure
# and returns the arguments.
# Arguments are returned as they could be modified by the middlewares.
def inner(handler):
async def async_inner_handler(*args):
await handler(args)
return args

def inner_handler(*args):
handler(*args)
return args

if asyncio.iscoroutinefunction(handler):
self.add_middleware_route("AFTER_REQUEST", endpoint, async_inner_handler)
else:
self.add_middleware_route("AFTER_REQUEST", endpoint, inner_handler)

return inner
return self.middleware_router.add_after_request(endpoint)

def add_directory(
self, route, directory_path, index_file=None, show_files_listing=False
Expand All @@ -149,7 +78,7 @@ def add_header(self, key, value):
self.headers.append((key, value))

def add_web_socket(self, endpoint, ws):
self.web_sockets[endpoint] = ws
self.web_socket_router.add_route(endpoint, ws)

def _add_event_handler(self, event_type: str, handler):
print(f"Add event {event_type} handler")
Expand All @@ -174,17 +103,16 @@ def start(self, url="127.0.0.1", port=5000):
if not self.dev:
workers = self.workers
socket = SocketHeld(url, port)
print(self.middlewares)
for _ in range(self.processes):
copied_socket = socket.try_clone()
p = Process(
target=spawn_process,
args=(
self.directories,
self.headers,
self.routes,
self.middlewares,
self.web_sockets,
self.router.get_routes(),
self.middleware_router.get_routes(),
self.web_socket_router.get_routes(),
self.event_handlers,
copied_socket,
workers,
Expand Down Expand Up @@ -217,7 +145,7 @@ def get(self, endpoint):
"""

def inner(handler):
self.add_route("GET", endpoint, handler)
self._add_route("GET", endpoint, handler)

return inner

Expand All @@ -229,7 +157,7 @@ def post(self, endpoint):
"""

def inner(handler):
self.add_route("POST", endpoint, handler)
self._add_route("POST", endpoint, handler)

return inner

Expand All @@ -241,7 +169,7 @@ def put(self, endpoint):
"""

def inner(handler):
self.add_route("PUT", endpoint, handler)
self._add_route("PUT", endpoint, handler)

return inner

Expand All @@ -253,7 +181,7 @@ def delete(self, endpoint):
"""

def inner(handler):
self.add_route("DELETE", endpoint, handler)
self._add_route("DELETE", endpoint, handler)

return inner

Expand All @@ -265,7 +193,7 @@ def patch(self, endpoint):
"""

def inner(handler):
self.add_route("PATCH", endpoint, handler)
self._add_route("PATCH", endpoint, handler)

return inner

Expand All @@ -277,7 +205,7 @@ def head(self, endpoint):
"""

def inner(handler):
self.add_route("HEAD", endpoint, handler)
self._add_route("HEAD", endpoint, handler)

return inner

Expand All @@ -289,7 +217,7 @@ def options(self, endpoint):
"""

def inner(handler):
self.add_route("OPTIONS", endpoint, handler)
self._add_route("OPTIONS", endpoint, handler)

return inner

Expand All @@ -301,7 +229,7 @@ def connect(self, endpoint):
"""

def inner(handler):
self.add_route("CONNECT", endpoint, handler)
self._add_route("CONNECT", endpoint, handler)

return inner

Expand All @@ -313,6 +241,6 @@ def trace(self, endpoint):
"""

def inner(handler):
self.add_route("TRACE", endpoint, handler)
self._add_route("TRACE", endpoint, handler)

return inner
7 changes: 5 additions & 2 deletions robyn/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ def static_file(file_path):
"""

return {
"response_type": "static_file",
"file_path": file_path
"type": "static_file",
"file_path": file_path,
# this is a hack for now
"body": "",
"status_code": "200",
}


Expand Down
Loading