Skip to content

Fix path_template variable parsing containing dots #2440

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 11 additions & 20 deletions dash/_pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from os.path import isfile, join
import collections
from urllib.parse import parse_qs
from fnmatch import fnmatch
import re
import flask

Expand Down Expand Up @@ -101,23 +100,18 @@ def _parse_path_variables(pathname, path_template):
returns **{"asset_id": "a100"}
"""

# parse variable definitions e.g. <var_name> from template
# and create pattern to match
wildcard_pattern = re.sub("<.*?>", "*", path_template)
var_pattern = re.sub("<.*?>", "(.*)", path_template)
# Copy of re._special_chars_map from Python >= 3.7 for backwards compatibility with 3.6
_special_chars_map = {i: '\\' + chr(i) for i in b'()[]{}?*+-|^$\\.&~# \t\n\r\v\f'}
escaped_template = path_template.translate(_special_chars_map)

# check that static sections of the pathname match the template
if not fnmatch(pathname, wildcard_pattern):
return None

# parse variable names e.g. var_name from template
var_names = re.findall("<(.*?)>", path_template)

# parse variables from path
variables = re.findall(var_pattern, pathname)
variables = variables[0] if isinstance(variables[0], tuple) else variables

return dict(zip(var_names, variables))
pattern = re.compile(
re.sub(
"<(?P<var>.*?)>", r"(?P<\g<var>>.*)",
escaped_template
)
)
match = pattern.match(pathname)
return match.groupdict() if match else None


def _create_redirect_function(redirect_to):
Expand Down Expand Up @@ -305,9 +299,6 @@ def register_page(

PAGE_REGISTRY[module] = page

if page["path_template"]:
_validate.validate_template(page["path_template"])

if layout is not None:
# Override the layout found in the file set during `plug`
PAGE_REGISTRY[module]["layout"] = layout
Expand Down
11 changes: 0 additions & 11 deletions dash/_validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,17 +421,6 @@ def validate_layout(layout, layout_value):
)
component_ids.add(component_id)


def validate_template(template):
variable_names = re.findall("<(.*?)>", template)

for name in variable_names:
if not name.isidentifier() or iskeyword(name):
raise Exception(
f'`{name}` is not a valid Python variable name in `path_template`: "{template}".'
)


def check_for_duplicate_pathnames(registry):
path_to_module = {}
for page in registry.values():
Expand Down
29 changes: 18 additions & 11 deletions dash/dash.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@
from dash import html
from dash import dash_table

from werkzeug.routing import Map, Rule
from werkzeug.exceptions import NotFound


from .fingerprint import build_fingerprint, check_fingerprint
from .resources import Scripts, Css
from .dependencies import (
Expand Down Expand Up @@ -2031,18 +2035,21 @@ def _import_layouts_from_pages(self):
page_module, "layout"
)

@staticmethod
def _path_to_page(path_id):
path_variables = None
for page in _pages.PAGE_REGISTRY.values():
def _path_to_page(self, path_id):
path_map = Map()
for module, page in _pages.PAGE_REGISTRY.items():
path_map.add(Rule(page['path'], endpoint=module))
if page["path_template"]:
template_id = page["path_template"].strip("/")
path_variables = _parse_path_variables(path_id, template_id)
if path_variables:
return page, path_variables
if path_id == page["path"].strip("/"):
return page, path_variables
return {}, None
path_map.add(Rule(page['path_template'], endpoint=module))

routes = path_map.bind(flask.request.base_url)

try:
module, args = routes.match(path_id)
return _pages.PAGE_REGISTRY[module], args
except NotFound as e:
self.logger.exception('Invalid page route')
return {}, None

def enable_pages(self):
if not self.use_pages:
Expand Down
21 changes: 21 additions & 0 deletions tests/unit/test_path_template.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from dash._pages import _parse_path_variables


def test_path_template_general():
path_template = "some/<var>/static"
assert _parse_path_variables("some/value/static", path_template) == {'var': 'value'}


def test_path_template():
path_template = "<foo>/<bar>"
assert _parse_path_variables("one/two", path_template) == {'foo': 'one', 'bar': 'two'}


def test_path_template_dots():
path_template = "<foo>.<bar>"
assert _parse_path_variables("one.two", path_template) == {'foo': 'one', 'bar': 'two'}


def test_path_template_none():
path_template = "novars"
assert _parse_path_variables("one/two", path_template) is None