Delay route compilation to allow late register_type calls
This commit is contained in:
@@ -1,2 +1,2 @@
|
||||
from microdot.microdot import Microdot, Request, Response, abort, redirect, \
|
||||
send_file # noqa: F401
|
||||
send_file, URLPattern # noqa: F401
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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/<foo/bar')
|
||||
self.assertRaises(ValueError, URLPattern, '/users/<badtype:id>')
|
||||
p = URLPattern('/users/<foo/bar')
|
||||
self.assertRaises(ValueError, p.compile)
|
||||
p = URLPattern('/users/<badtype:id>')
|
||||
self.assertRaises(ValueError, p.compile)
|
||||
|
||||
def test_custom_url_pattern(self):
|
||||
URLPattern.register_type('hex', '[0-9a-f]+')
|
||||
|
||||
Reference in New Issue
Block a user