Created
July 11, 2009 11:05
-
-
Save ikasamt/145225 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Rule(object): | |
""" Handles each routing rule. """ | |
def __init__(self, pattern, **param): | |
super(Rule, self).__init__() | |
self.pattern = pattern[:-1] if pattern.endswith('/') else pattern | |
self.regex = self.pattern | |
self.param = param | |
self.matches = re.findall(':([^/.]+)', self.pattern) | |
for i in range(len(self.matches)): | |
self.regex = self.regex.replace(':' + self.matches[i], '([^/.]+)') | |
self.param[self.matches[i]] = None #i | |
self.validate() | |
def __eq__(self, other): | |
return self.regex == other.regex | |
def __getattr__(self, attr): | |
try: | |
return getattr(self, 'param')[attr] | |
except KeyError: | |
raise AttributeError, attr | |
def __str__(self): | |
from operator import itemgetter | |
return ', '.join(['%s: %s' % (k, v) for k, v in \ | |
sorted(self.param.items(), key = itemgetter(1))]) | |
def match_url(self, url): | |
if url.endswith('/'): | |
url = url[:-1] | |
try: | |
mat = re.findall(self.regex, url)[0] | |
except IndexError: | |
return None | |
param = copy(self.param) | |
if isinstance(mat, basestring): | |
if self.matches: | |
param[self.matches[0]] = mat | |
elif isinstance(mat, tuple): | |
for i in range(len(mat)): | |
param[self.matches[i]] = mat[i] | |
return param | |
def url_for(self, controller, **param): | |
logging.info('xxxxxxxxxx') | |
logging.info(self.param) | |
logging.info('yyyyyyy') | |
param['controller'] = controller | |
url = self.pattern | |
if self.pattern == '': | |
url = '/' | |
for match in self.matches: | |
#if match not in param: | |
# return None | |
if match in param: | |
url = url.replace(':' + match, str(param[match])) | |
del param[match] | |
# extra parameters | |
ep = '&'.join(['%s=%s' % (k, v) for k, v in param.items() if k not in self.param]) | |
for k,v in self.param.items(): | |
if v is not None: | |
if not param.has_key(k) or v != param[k]: | |
return None | |
url = re.sub(':[^./]*', '', url) | |
return url + '?' + ep if ep else url | |
def validate(self): | |
if 'controller' not in self.param: | |
raise RuleNoControllerError | |
if 'action' not in self.param: | |
self.param['action'] = 'index' | |
if not self.regex.startswith('^'): | |
self.regex = '^' + self.regex | |
if not self.regex.endswith('$'): | |
self.regex = self.regex + '$' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment