|
1 | 1 | from asyncio import get_event_loop, start_server |
2 | 2 | from os import stat |
3 | | -from re import match, search |
| 3 | +from re import search |
4 | 4 |
|
5 | 5 | class Thimble: |
6 | 6 | """ |
@@ -356,28 +356,41 @@ def add_route(func): |
356 | 356 |
|
357 | 357 | return add_route |
358 | 358 |
|
359 | | - def resolve_route(self, route_pattern): |
| 359 | + def resolve_route(self, route_candidate): |
360 | 360 | """ |
361 | 361 | Given a route pattern (METHOD + url_path), look up the corresponding function. |
362 | 362 |
|
363 | 363 | 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+])$) |
365 | 365 |
|
366 | 366 | Returns: |
367 | 367 | object: reference to function (for non-regex URLs) or tuple with function and regex capture (for regex URLs) |
368 | 368 | """ |
369 | 369 | 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] |
372 | 376 | 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) |
375 | 383 | 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] |
377 | 387 | wildcard_value = regex_match.group(1) |
378 | 388 | if self.debug: |
379 | | - print(f'Wildcard match: {wildcard_value}') |
| 389 | + print(f'Extracted wildcard value: {wildcard_value}') |
380 | 390 | result = func, wildcard_value |
| 391 | + else: |
| 392 | + if self.debug: |
| 393 | + print("No match.") |
381 | 394 |
|
382 | 395 | return result |
383 | 396 |
|
@@ -451,3 +464,4 @@ def run(self, host='0.0.0.0', port=80, loop=None, debug=False): |
451 | 464 | loop.create_task(server) |
452 | 465 |
|
453 | 466 | return loop |
| 467 | + |
0 commit comments