plain 0.21.5__py3-none-any.whl → 0.22.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
plain/urls/patterns.py ADDED
@@ -0,0 +1,271 @@
1
+ import functools
2
+ import inspect
3
+ import re
4
+ import string
5
+
6
+ from plain.exceptions import ImproperlyConfigured
7
+ from plain.preflight import Error, Warning
8
+ from plain.runtime import settings
9
+ from plain.utils.functional import cached_property
10
+ from plain.utils.regex_helper import _lazy_re_compile
11
+
12
+ from .converters import get_converter
13
+
14
+
15
+ class CheckURLMixin:
16
+ def describe(self):
17
+ """
18
+ Format the URL pattern for display in warning messages.
19
+ """
20
+ description = f"'{self}'"
21
+ if self.name:
22
+ description += f" [name='{self.name}']"
23
+ return description
24
+
25
+ def _check_pattern_startswith_slash(self):
26
+ """
27
+ Check that the pattern does not begin with a forward slash.
28
+ """
29
+ regex_pattern = self.regex.pattern
30
+ if not settings.APPEND_SLASH:
31
+ # Skip check as it can be useful to start a URL pattern with a slash
32
+ # when APPEND_SLASH=False.
33
+ return []
34
+ if regex_pattern.startswith(("/", "^/", "^\\/")) and not regex_pattern.endswith(
35
+ "/"
36
+ ):
37
+ warning = Warning(
38
+ f"Your URL pattern {self.describe()} has a route beginning with a '/'. Remove this "
39
+ "slash as it is unnecessary. If this pattern is targeted in an "
40
+ "include(), ensure the include() pattern has a trailing '/'.",
41
+ id="urls.W002",
42
+ )
43
+ return [warning]
44
+ else:
45
+ return []
46
+
47
+
48
+ class RegexPattern(CheckURLMixin):
49
+ def __init__(self, regex, name=None, is_endpoint=False):
50
+ self._regex = regex
51
+ self._regex_dict = {}
52
+ self._is_endpoint = is_endpoint
53
+ self.name = name
54
+ self.converters = {}
55
+ self.regex = self._compile(str(regex))
56
+
57
+ def match(self, path):
58
+ match = (
59
+ self.regex.fullmatch(path)
60
+ if self._is_endpoint and self.regex.pattern.endswith("$")
61
+ else self.regex.search(path)
62
+ )
63
+ if match:
64
+ # If there are any named groups, use those as kwargs, ignoring
65
+ # non-named groups. Otherwise, pass all non-named arguments as
66
+ # positional arguments.
67
+ kwargs = match.groupdict()
68
+ args = () if kwargs else match.groups()
69
+ kwargs = {k: v for k, v in kwargs.items() if v is not None}
70
+ return path[match.end() :], args, kwargs
71
+ return None
72
+
73
+ def check(self):
74
+ warnings = []
75
+ warnings.extend(self._check_pattern_startswith_slash())
76
+ if not self._is_endpoint:
77
+ warnings.extend(self._check_include_trailing_dollar())
78
+ return warnings
79
+
80
+ def _check_include_trailing_dollar(self):
81
+ regex_pattern = self.regex.pattern
82
+ if regex_pattern.endswith("$") and not regex_pattern.endswith(r"\$"):
83
+ return [
84
+ Warning(
85
+ f"Your URL pattern {self.describe()} uses include with a route ending with a '$'. "
86
+ "Remove the dollar from the route to avoid problems including "
87
+ "URLs.",
88
+ id="urls.W001",
89
+ )
90
+ ]
91
+ else:
92
+ return []
93
+
94
+ def _compile(self, regex):
95
+ """Compile and return the given regular expression."""
96
+ try:
97
+ return re.compile(regex)
98
+ except re.error as e:
99
+ raise ImproperlyConfigured(
100
+ f'"{regex}" is not a valid regular expression: {e}'
101
+ ) from e
102
+
103
+ def __str__(self):
104
+ return str(self._regex)
105
+
106
+
107
+ _PATH_PARAMETER_COMPONENT_RE = _lazy_re_compile(
108
+ r"<(?:(?P<converter>[^>:]+):)?(?P<parameter>[^>]+)>"
109
+ )
110
+
111
+
112
+ def _route_to_regex(route, is_endpoint=False):
113
+ """
114
+ Convert a path pattern into a regular expression. Return the regular
115
+ expression and a dictionary mapping the capture names to the converters.
116
+ For example, 'foo/<int:pk>' returns '^foo\\/(?P<pk>[0-9]+)'
117
+ and {'pk': <plain.urls.converters.IntConverter>}.
118
+ """
119
+ original_route = route
120
+ parts = ["^"]
121
+ converters = {}
122
+ while True:
123
+ match = _PATH_PARAMETER_COMPONENT_RE.search(route)
124
+ if not match:
125
+ parts.append(re.escape(route))
126
+ break
127
+ elif not set(match.group()).isdisjoint(string.whitespace):
128
+ raise ImproperlyConfigured(
129
+ f"URL route '{original_route}' cannot contain whitespace in angle brackets "
130
+ "<…>."
131
+ )
132
+ parts.append(re.escape(route[: match.start()]))
133
+ route = route[match.end() :]
134
+ parameter = match["parameter"]
135
+ if not parameter.isidentifier():
136
+ raise ImproperlyConfigured(
137
+ f"URL route '{original_route}' uses parameter name {parameter!r} which isn't a valid "
138
+ "Python identifier."
139
+ )
140
+ raw_converter = match["converter"]
141
+ if raw_converter is None:
142
+ # If a converter isn't specified, the default is `str`.
143
+ raw_converter = "str"
144
+ try:
145
+ converter = get_converter(raw_converter)
146
+ except KeyError as e:
147
+ raise ImproperlyConfigured(
148
+ f"URL route {original_route!r} uses invalid converter {raw_converter!r}."
149
+ ) from e
150
+ converters[parameter] = converter
151
+ parts.append("(?P<" + parameter + ">" + converter.regex + ")")
152
+ if is_endpoint:
153
+ parts.append(r"\Z")
154
+ return "".join(parts), converters
155
+
156
+
157
+ class RoutePattern(CheckURLMixin):
158
+ def __init__(self, route, name=None, is_endpoint=False):
159
+ self._route = route
160
+ self._regex_dict = {}
161
+ self._is_endpoint = is_endpoint
162
+ self.name = name
163
+ self.converters = _route_to_regex(str(route), is_endpoint)[1]
164
+ self.regex = self._compile(str(route))
165
+
166
+ def match(self, path):
167
+ match = self.regex.search(path)
168
+ if match:
169
+ # RoutePattern doesn't allow non-named groups so args are ignored.
170
+ kwargs = match.groupdict()
171
+ for key, value in kwargs.items():
172
+ converter = self.converters[key]
173
+ try:
174
+ kwargs[key] = converter.to_python(value)
175
+ except ValueError:
176
+ return None
177
+ return path[match.end() :], (), kwargs
178
+ return None
179
+
180
+ def check(self):
181
+ warnings = self._check_pattern_startswith_slash()
182
+ route = self._route
183
+ if "(?P<" in route or route.startswith("^") or route.endswith("$"):
184
+ warnings.append(
185
+ Warning(
186
+ f"Your URL pattern {self.describe()} has a route that contains '(?P<', begins "
187
+ "with a '^', or ends with a '$'. This was likely an oversight "
188
+ "when migrating to plain.urls.path().",
189
+ id="2_0.W001",
190
+ )
191
+ )
192
+ return warnings
193
+
194
+ def _compile(self, route):
195
+ return re.compile(_route_to_regex(route, self._is_endpoint)[0])
196
+
197
+ def __str__(self):
198
+ return str(self._route)
199
+
200
+
201
+ class URLPattern:
202
+ def __init__(self, *, pattern, view, name=None):
203
+ self.pattern = pattern
204
+ self.view = view
205
+ self.name = name
206
+
207
+ def __repr__(self):
208
+ return f"<{self.__class__.__name__} {self.pattern.describe()}>"
209
+
210
+ def check(self):
211
+ warnings = self._check_pattern_name()
212
+ warnings.extend(self.pattern.check())
213
+ return warnings
214
+
215
+ def _check_pattern_name(self):
216
+ """
217
+ Check that the pattern name does not contain a colon.
218
+ """
219
+ if self.pattern.name is not None and ":" in self.pattern.name:
220
+ warning = Warning(
221
+ f"Your URL pattern {self.pattern.describe()} has a name including a ':'. Remove the colon, to "
222
+ "avoid ambiguous namespace references.",
223
+ id="urls.W003",
224
+ )
225
+ return [warning]
226
+ else:
227
+ return []
228
+
229
+ def _check_view(self):
230
+ from plain.views import View
231
+
232
+ view = self.view
233
+ if inspect.isclass(view) and issubclass(view, View):
234
+ return [
235
+ Error(
236
+ f"Your URL pattern {self.pattern.describe()} has an invalid view, pass {view.__name__}.as_view() "
237
+ f"instead of {view.__name__}.",
238
+ id="urls.E009",
239
+ )
240
+ ]
241
+ return []
242
+
243
+ def resolve(self, path):
244
+ match = self.pattern.match(path)
245
+ if match:
246
+ new_path, args, captured_kwargs = match
247
+ from .resolvers import ResolverMatch
248
+
249
+ return ResolverMatch(
250
+ self.view,
251
+ args,
252
+ captured_kwargs,
253
+ self.pattern.name,
254
+ route=str(self.pattern),
255
+ captured_kwargs=captured_kwargs,
256
+ )
257
+
258
+ @cached_property
259
+ def lookup_str(self):
260
+ """
261
+ A string that identifies the view (e.g. 'path.to.view_function' or
262
+ 'path.to.ClassBasedView').
263
+ """
264
+ view = self.view
265
+ if isinstance(view, functools.partial):
266
+ view = view.func
267
+ if hasattr(view, "view_class"):
268
+ view = view.view_class
269
+ elif not hasattr(view, "__name__"):
270
+ return view.__module__ + "." + view.__class__.__name__
271
+ return view.__module__ + "." + view.__qualname__