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

- [ERROR] Error handling request /favicon.ico #73 #74

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
100 changes: 34 additions & 66 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 16 additions & 13 deletions bobtail/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class Parser:
meta_data: Dict = None

def __init__(self, routes: List[Route], path):
self.path = path
self.path = path or "/"
self.routes = routes

def _match(self) -> Dict:
Expand Down Expand Up @@ -57,19 +57,20 @@ def _match(self) -> Dict:
self._set_metadata(k, path_segment, None, None)
return self.meta_data["routes"][k]
# Test route matches path
if route_segment[0] != "{" and route_segment != path_segment:
if route_segment == "*":
self.meta_data["matched"] = k
return self.meta_data["routes"][k]
# No match, break out of this route class
break
if route_segment[0] == "{":
# If we reach this point then store the vars
n, t = route_segment[1:-1].split(":")
self._set_metadata(k, path_segment, t, n)
if route_segment:
if route_segment[0] != "{" and route_segment != path_segment:
if route_segment == "*":
self.meta_data["matched"] = k
return self.meta_data["routes"][k]
# No match, break out of this route class
break
if route_segment[0] == "{":
# If we reach this point then store the vars
n, t = route_segment[1:-1].split(":")
self._set_metadata(k, path_segment, t, n)
if (len(split_path_vals) - 1) == i:
self.meta_data["matched"] = k
return self.meta_data["routes"][k]
if self.meta_data["routes"][k]["route"] == self.path:
self.meta_data["matched"] = k

def _set_metadata(
self,
Expand Down Expand Up @@ -130,4 +131,6 @@ def get_matched(self) -> Optional[str]:
:return:
:rtype:
"""
if not self.meta_data or "matched" not in self.meta_data:
return None
return self.meta_data["matched"]
7 changes: 7 additions & 0 deletions bobtail/route.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,10 @@ def delete(self, req: Request, res: Response) -> None:

Handler = TypeVar("Handler", Callable[[Request, Response], None], None)
Route = TypeVar("Route", Tuple[AbstractRoute, str], None)


def create_favicon_route():
class FaviconRoute:
def get(self, req: Request, res: Response):
res.set_status(404)
return FaviconRoute()
23 changes: 21 additions & 2 deletions bobtail/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from bobtail.request import Request
from bobtail.status import Status
from bobtail.exceptions import NoRoutesError, RouteClassError
from bobtail.route import Route, Handler
from bobtail.route import Route, Handler, create_favicon_route
from bobtail.parser import Parser
from bobtail.middleware import Middleware
from bobtail.headers import ResponseHeaders, RequestHeaders
Expand Down Expand Up @@ -59,9 +59,15 @@ def __init__(self, *args, **kwargs):
if "routes" not in kwargs:
raise NoRoutesError("Expected a list of routes")
self.routes = kwargs["routes"]
# append a default favicon route to set status to 404
default_fav = self._default_favicon_route(self.routes)
if default_fav:
self.routes.append(default_fav)
_options = kwargs.get("options")
if _options:
self.options = _options
else:
self.options = BaseOptions()
self.middleware = Middleware()

def _handle_404(self, req: Request, res: Response):
Expand Down Expand Up @@ -92,12 +98,14 @@ def _call_handler(self, route: callable, method: str):
def _handle_route(self):
p = Parser(self.routes, self.request.path)
self.parse_metadata = p.route()
print("wsgi , p ---> ", p.meta_data)
# Set the args on the request object
if self.parse_metadata and "vars" in self.parse_metadata:
self.request.set_args(self.parse_metadata["vars"])
for current_route in self.routes:
route, _ = current_route
if route.__class__.__name__ == p.get_matched():
matched_route = p.get_matched()
if route.__class__.__name__ == matched_route:
match self.request.method:
case "GET":
self._call_handler(route, "get")
Expand All @@ -114,6 +122,10 @@ def _handle_route(self):
case "PATCH":
self._call_handler(route, "patch")
return
# If there are no matches & no 404 route set status to 404
if p.get_matched() is None:
self.response.status = 404

self.middleware.call(self.request, self.response, self._handle_404)

def __call__(self, environ, start_response):
Expand Down Expand Up @@ -172,3 +184,10 @@ def run(self, req: Request, res: Response, tail: Tail) -> None:
:return: None
"""
self.middleware.add(middleware)

@staticmethod
def _default_favicon_route(routes: List[Route]) -> Route:
for r in routes:
if r[1] == "/favicon.ico":
return None
return create_favicon_route(), "/favicon.ico"
25 changes: 25 additions & 0 deletions tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,31 @@ def get(self, req, res):
}
assert result == expected

def test_route_index_route2(self):
class Route1:
def get(self, req, res):
res.set_status(201)

class Route2:
def get(self, req, res):
res.set_status(202)

_routes3 = [
(Route2(), "/"),
(Route1(), "/route2"),
]
path = ""
p3 = Parser(_routes3, path)
result = p3.route()
expected = {
'class': 'Route2',
'path': '/',
'route': '/',
'split': [''],
'vars': None,
}
assert result == expected

def test_extra_segments(self):
class Images6:
def get(self, req, res):
Expand Down
3 changes: 2 additions & 1 deletion tests/test_wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class Images:

def get(self, req, res):
res.set_headers({"Content-type": "text/plain"})
res.set_status(200)
res.set_status(202)
res.set_body({})

routes = [
Expand All @@ -42,6 +42,7 @@ def get(self, req, res):
env = environ()
_ = self.app(env, lambda s, r: None)
assert self.app.response.headers["Access-Control-Allow-Origin"] == "*"
assert self.app.response.status == 202

def test_handlers_get(self, bobtail_app, route_class_one, environ):

Expand Down