From aa76e6378b37faab52008a8aab8db75f81b29323 Mon Sep 17 00:00:00 2001 From: Miguel Grinberg Date: Mon, 3 Mar 2025 19:10:33 +0000 Subject: [PATCH] Delay route compilation to allow late register_type calls --- src/microdot/__init__.py | 2 +- src/microdot/microdot.py | 7 +++++-- tests/test_url_pattern.py | 6 ++++-- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/microdot/__init__.py b/src/microdot/__init__.py index b619686..f0fc5bd 100644 --- a/src/microdot/__init__.py +++ b/src/microdot/__init__.py @@ -1,2 +1,2 @@ from microdot.microdot import Microdot, Request, Response, abort, redirect, \ - send_file # noqa: F401 + send_file, URLPattern # noqa: F401 diff --git a/src/microdot/microdot.py b/src/microdot/microdot.py index e8bdcaa..a21467e 100644 --- a/src/microdot/microdot.py +++ b/src/microdot/microdot.py @@ -819,8 +819,10 @@ class URLPattern(): self.url_pattern = url_pattern self.segments = [] self.regex = None + + def compile(self): pattern = '' - for segment in url_pattern.lstrip('/').split('/'): + for segment in self.url_pattern.lstrip('/').split('/'): if segment and segment[0] == '<': if segment[-1] != '>': raise ValueError('invalid URL pattern') @@ -844,6 +846,7 @@ class URLPattern(): pattern += '/' + segment self.segments.append({'parser': None}) self.regex = re.compile('^' + pattern + '$') + return self.regex @classmethod def register_type(cls, type_name, pattern='[^/]+', parser=None): @@ -852,7 +855,7 @@ class URLPattern(): def match(self, path): args = {} - g = self.regex.match(path) + g = (self.regex or self.compile()).match(path) if not g: return i = 1 diff --git a/tests/test_url_pattern.py b/tests/test_url_pattern.py index c3656bd..48ebde4 100644 --- a/tests/test_url_pattern.py +++ b/tests/test_url_pattern.py @@ -119,8 +119,10 @@ class TestURLPattern(unittest.TestCase): self.assertIsNone(p.match('/foo/abc/def/123/test')) def test_invalid_url_patterns(self): - self.assertRaises(ValueError, URLPattern, '/users/') + p = URLPattern('/users/') + self.assertRaises(ValueError, p.compile) def test_custom_url_pattern(self): URLPattern.register_type('hex', '[0-9a-f]+')