diff --git a/sanic/router.py b/sanic/router.py index b601622c..0af1d13d 100644 --- a/sanic/router.py +++ b/sanic/router.py @@ -65,7 +65,7 @@ class Router: routes_always_check = None parameter_pattern = re.compile(r'<(.+?)>') - def __init__(self): + def __init__(self, converters=None): self.routes_all = {} self.routes_names = {} self.routes_static_files = {} @@ -73,9 +73,11 @@ class Router: self.routes_dynamic = defaultdict(list) self.routes_always_check = [] self.hosts = set() + self._converters = REGEX_TYPES + if converters: + self._converters.update(converters) - @classmethod - def parse_parameter_string(cls, parameter_string): + def parse_parameter_string(self, parameter_string): """Parse a parameter string into its constituent name, type, and pattern @@ -100,7 +102,7 @@ class Router: default = (str, pattern) # Pull from pre-configured types - _type, pattern = REGEX_TYPES.get(pattern, default) + _type, pattern = self._converters.get(pattern, default) return name, _type, pattern diff --git a/tests/test_routes.py b/tests/test_routes.py index b6b62283..39aa5566 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -3,7 +3,7 @@ import pytest from sanic import Sanic from sanic.response import text -from sanic.router import RouteExists, RouteDoesNotExist +from sanic.router import RouteExists, RouteDoesNotExist, Router from sanic.constants import HTTP_METHODS @@ -850,3 +850,23 @@ def test_unmergeable_overload_routes(): request, response = app.test_client.post('/overload_part') assert response.status == 405 + + +def test_custom_route_converters(): + regex = r'[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-' \ + r'[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}' + custom_router = Router(converters={ + "uuid": (uuid.UUID, regex) + }) + app = Sanic('test_dynamic_route', router=custom_router) + results = [] + + @app.route('/', methods=None) + async def handler(request, id): + results.append(id) + return text('OK') + + request, response = app.test_client.get('/folder/test123') + + assert response.text == 'OK' + assert isinstance(results[0], uuid.UUID)