Skip to content

Commit 4b6b122

Browse files
thimble.py - rework resolve_route() better debug and closes issue #17
1 parent ae14a2f commit 4b6b122

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

thimble.py

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from asyncio import get_event_loop, start_server
22
from os import stat
3-
from re import match, search
3+
from re import search
44

55
class Thimble:
66
"""
@@ -356,28 +356,41 @@ def add_route(func):
356356

357357
return add_route
358358

359-
def resolve_route(self, route_pattern):
359+
def resolve_route(self, route_candidate):
360360
"""
361361
Given a route pattern (METHOD + url_path), look up the corresponding function.
362362
363363
Args:
364-
route_pattern (string): An uppercase HTTP method concatenated with a URL path wich may contain regex (ex: GET/gpio/([0-9+])$)
364+
route_candidate (string): An uppercase HTTP method concatenated with a URL path wich may contain regex (ex: GET/gpio/([0-9+])$)
365365
366366
Returns:
367367
object: reference to function (for non-regex URLs) or tuple with function and regex capture (for regex URLs)
368368
"""
369369
result = None
370-
if route_pattern in self.routes: # pattern is a fixed string, like: 'GET/gpio/2'
371-
result = self.routes[route_pattern]
370+
if self.debug:
371+
print("Looking for a route matching:", route_candidate)
372+
if route_candidate in self.routes: # pattern is a non-regex string, like: 'GET/gpio/2'
373+
if self.debug:
374+
print("Route table had an exact match. We're done!")
375+
result = self.routes[route_candidate]
372376
else: # pattern may contain regex, like 'GET/gpio/([0-9]+)'
373-
for key in self.routes.keys():
374-
regex_match = match(key, route_pattern)
377+
if self.debug:
378+
print("No exact match in route table. Looking for regex matches...")
379+
for stored_route in self.routes.keys():
380+
if self.debug:
381+
print("Examining this route table entry for potential match:", stored_route)
382+
regex_match = search("^" + stored_route + "$", route_candidate)
375383
if regex_match:
376-
func = self.routes[key]
384+
if self.debug:
385+
print("Found a regex match with:", stored_route)
386+
func = self.routes[stored_route]
377387
wildcard_value = regex_match.group(1)
378388
if self.debug:
379-
print(f'Wildcard match: {wildcard_value}')
389+
print(f'Extracted wildcard value: {wildcard_value}')
380390
result = func, wildcard_value
391+
else:
392+
if self.debug:
393+
print("No match.")
381394

382395
return result
383396

@@ -451,3 +464,4 @@ def run(self, host='0.0.0.0', port=80, loop=None, debug=False):
451464
loop.create_task(server)
452465

453466
return loop
467+

0 commit comments

Comments
 (0)