Skip to content

Commit

Permalink
Add casting to regex matching (#52)
Browse files Browse the repository at this point in the history
  • Loading branch information
ahopkins authored Feb 24, 2022
1 parent c2ecea9 commit 15ddf4c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
18 changes: 12 additions & 6 deletions sanic_routing/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,19 @@ def resolve(
allowed_methods=route.methods,
)

# Regex routes evaluate and can extract params directly. They are set
# on param_basket["__params__"]
# Convert matched values to parameters
params = param_basket["__params__"]
if not params:
# If param_basket["__params__"] does not exist, we might have
# param_basket["__matches__"], which are indexed based matches
# on path segments. They should already be cast types.
if route.regex:
params.update(
{
param.name: param.cast(
param_basket["__params__"][param.name]
)
for param in route.params.values()
if param.cast is not str
}
)
elif param_basket["__matches__"]:
params = {
param.name: param_basket["__matches__"][idx]
for idx, param in route.params.items()
Expand Down
3 changes: 1 addition & 2 deletions tests/test_routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from datetime import date

import pytest

from sanic_routing import BaseRouter
from sanic_routing.exceptions import NoMethod, NotFound, RouteExists

Expand Down Expand Up @@ -479,7 +478,7 @@ def handler2():

_, handler, params = router.get(f"/api/3/hello_world/{uri}", "GET")
assert handler() == "handler2"
assert params == {"version": "3", "foo": uri}
assert params == {"version": 3, "foo": uri}


@pytest.mark.parametrize("uri", ("a-random-path", "a/random/path"))
Expand Down

0 comments on commit 15ddf4c

Please sign in to comment.