Mercurial > p > roundup > code
comparison roundup/web/router.py @ 4909:f31c93abedf6 routing
routing: No leading slash in URL map patterns
| author | anatoly techtonik <techtonik@gmail.com> |
|---|---|
| date | Wed, 16 Jul 2014 03:17:54 +0300 |
| parents | c37069a99cec |
| children | e5f90a69f660 |
comparison
equal
deleted
inserted
replaced
| 4908:92757447dcf0 | 4909:f31c93abedf6 |
|---|---|
| 20 return self.name | 20 return self.name |
| 21 | 21 |
| 22 ExampleHandler = NamedObject('ExampleHandler') | 22 ExampleHandler = NamedObject('ExampleHandler') |
| 23 ExampleFileHandler = NamedObject('ExampleFileHandler') | 23 ExampleFileHandler = NamedObject('ExampleFileHandler') |
| 24 | 24 |
| 25 | |
| 25 EXAMPLE_URLMAP = ( | 26 EXAMPLE_URLMAP = ( |
| 26 '/static/(.*)', ExampleFileHandler, | 27 'static/(.*)', ExampleFileHandler, |
| 27 '/', ExampleHandler | 28 '', ExampleHandler |
| 28 ) | 29 ) |
| 29 | 30 |
| 30 | 31 |
| 31 # --- Regexp based router | 32 # --- Regexp based router |
| 32 | 33 |
| 33 class Router(object): | 34 class Router(object): |
| 34 | 35 |
| 35 def __init__(self, urlmap=[]): | 36 def __init__(self, urlmap=[]): |
| 36 """ | 37 """ |
| 37 `urlmap` is a list (pattern, handler, pattern, ...) | 38 `urlmap` is a list (pattern, handler, pattern, ...) |
| 39 pattern should have no leading slash | |
| 38 """ | 40 """ |
| 39 self.urlmap = urlmap | 41 self.urlmap = urlmap |
| 40 | 42 |
| 41 def get_handler(self, urlpath): | 43 def get_handler(self, urlpath): |
| 42 """ | 44 """ |
| 43 `urlpath` is a part of url /that/looks?like=this | 45 `urlpath` is a part of url /that/looks?like=this |
| 46 (leading slash is optional) | |
| 44 | 47 |
| 45 returns tuple (handler, arguments) or (None, ()) | 48 returns tuple (handler, arguments) or (None, ()) |
| 46 """ | 49 """ |
| 50 # strip leading slashes before matching | |
| 51 path = urlpath.lstrip('/') | |
| 47 for i in range(0, len(self.urlmap), 2): | 52 for i in range(0, len(self.urlmap), 2): |
| 48 pattern, handler = self.urlmap[i], self.urlmap[i+1] | 53 pattern, handler = self.urlmap[i], self.urlmap[i+1] |
| 49 match = re.match(pattern, urlpath) | 54 match = re.match(pattern, urlpath) |
| 50 if match: | 55 if match: |
| 51 return handler, match.groups() | 56 return handler, match.groups() |
