Skip to content
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

Fix #460 - missing parse_rule method #463

Merged
merged 3 commits into from
Sep 13, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
50 changes: 48 additions & 2 deletions flask_restx/swagger.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
from six import string_types, itervalues, iteritems, iterkeys

from flask import current_app
from werkzeug.routing import parse_rule

from . import fields
from .model import Model, ModelBase, OrderedModel
Expand All @@ -36,7 +35,6 @@
"default": "string",
}


#: Maps Python primitives types to Swagger ones
PY_TYPES = {
int: "integer",
Expand All @@ -55,6 +53,21 @@
r"^:raises\s+(?P<name>[\w\d_]+)\s*:\s*(?P<description>.*)$", re.MULTILINE
)

RE_PARSE_RULE = re.compile(
r"""
(?P<static>[^<]*) # static rule data
<
(?:
(?P<converter>[a-zA-Z_][a-zA-Z0-9_]*) # converter name
(?:\((?P<args>.*?)\))? # converter arguments
\: # variable delimiter
)?
(?P<variable>[a-zA-Z_][a-zA-Z0-9_]*) # variable name
>
""",
re.VERBOSE,
)


def ref(model):
"""Return a reference to model in definitions"""
Expand All @@ -74,6 +87,39 @@ def extract_path(path):
return RE_URL.sub(r"{\1}", path)


def parse_rule(rule):
"""
Parse a rule and return it as generator. Each iteration yields tuples in the form
``(converter, arguments, variable)``. If the converter is `None` it's a static url part, otherwise it's a dynamic
one.

Note: This originally lived in werkzeug.routing.parse_rule until it was removed in werkzeug 2.2.0.
"""
pos = 0
end = len(rule)
do_match = RE_PARSE_RULE.match
used_names = set()
while pos < end:
m = do_match(rule, pos)
if m is None:
break
data = m.groupdict()
if data["static"]:
yield None, None, data["static"]
variable = data["variable"]
converter = data["converter"] or "default"
if variable in used_names:
raise ValueError(f"variable name {variable!r} used twice.")
used_names.add(variable)
yield converter, data["args"] or None, variable
pos = m.end()
if pos < end:
remaining = rule[pos:]
if ">" in remaining or "<" in remaining:
raise ValueError(f"malformed url rule: {rule!r}")
yield None, None, remaining


def extract_path_params(path):
"""
Extract Flask-style parameters from an URL pattern as Swagger ones.
Expand Down