Skip to content
Merged
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
82 changes: 61 additions & 21 deletions openapi_core/templating/paths/parsers.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,73 @@
from typing import Any
# Allow writing union types as X | Y in Python 3.9
from __future__ import annotations

from parse import Parser
import re
from dataclasses import dataclass


class PathParameter:
name = "PathParameter"
pattern = r"[^\/]*"
@dataclass(frozen=True)
class PathMatchResult:
"""Result of path parsing."""

def __call__(self, text: str) -> str:
return text
named: dict[str, str]


class PathParser(Parser): # type: ignore
class PathParser:
"""Parses path patterns with parameters into regex and matches against URLs."""

parse_path_parameter = PathParameter()
_PARAM_PATTERN = r"[^/]*"

def __init__(
self, pattern: str, pre_expression: str = "", post_expression: str = ""
) -> None:
extra_types = {
self.parse_path_parameter.name: self.parse_path_parameter
}
super().__init__(pattern, extra_types)
self._expression: str = (
pre_expression + self._expression + post_expression
)
self.pattern = pattern
self._group_to_name: dict[str, str] = {}

regex_body = self._compile_template_to_regex(pattern)
self._expression = f"{pre_expression}{regex_body}{post_expression}"
self._compiled = re.compile(self._expression)

def search(self, text: str) -> PathMatchResult | None:
"""Searches for a match in the given text."""
match = self._compiled.search(text)
return self._to_result(match)

def parse(self, text: str) -> PathMatchResult | None:
"""Parses the entire text for a match."""
match = self._compiled.fullmatch(text)
return self._to_result(match)

def _handle_field(self, field: str) -> Any:
# handle as path parameter field
field = field[1:-1]
path_parameter_field = "{%s:PathParameter}" % field
return super()._handle_field(path_parameter_field)
def _compile_template_to_regex(self, template: str) -> str:
parts: list[str] = []
i = 0
group_index = 0
while i < len(template):
start = template.find("{", i)
if start == -1:
parts.append(re.escape(template[i:]))
break
end = template.find("}", start + 1)
if end == -1:
raise ValueError(f"Unmatched '{{' in template: {template!r}")

parts.append(re.escape(template[i:start]))
param_name = template[start + 1 : end]
group_name = f"g{group_index}"
group_index += 1
self._group_to_name[group_name] = param_name
parts.append(f"(?P<{group_name}>{self._PARAM_PATTERN})")
i = end + 1

return "".join(parts)

def _to_result(
self, match: re.Match[str] | None
) -> PathMatchResult | None:
if match is None:
return None
return PathMatchResult(
named={
param_name: match.group(group_name)
for group_name, param_name in self._group_to_name.items()
},
)
35 changes: 1 addition & 34 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ module = [
"isodate.*",
"jsonschema.*",
"more_itertools.*",
"parse.*",
"requests.*",
"werkzeug.*",
]
Expand Down Expand Up @@ -69,7 +68,6 @@ aiohttp = {version = ">=3.0", optional = true}
starlette = {version = ">=0.26.1,<0.50.0", optional = true}
isodate = "*"
more-itertools = "*"
parse = "*"
openapi-schema-validator = "^0.6.0"
openapi-spec-validator = "^0.7.1"
requests = {version = "*", optional = true}
Expand Down
7 changes: 0 additions & 7 deletions tests/unit/templating/test_paths_parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,6 @@ def test_chars_valid(self, path_pattern, expected):

assert result.named == expected

@pytest.mark.xfail(
reason=(
"Special characters of regex not supported. "
"See https://github.com/python-openapi/openapi-core/issues/672"
),
strict=True,
)
@pytest.mark.parametrize(
"path_pattern,expected",
[
Expand Down
Loading