Add support of custom routers rules

This commit is contained in:
Ivan Salamakha 2017-11-10 14:34:45 +02:00
parent 05bb812e2b
commit 51aec250b0
2 changed files with 27 additions and 5 deletions

View File

@ -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

View File

@ -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('/<id:uuid>', 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)