home *** CD-ROM | disk | FTP | other *** search
- # Source Generated with Decompyle++
- # File: in.pyc (Python 2.6)
-
- import re
- import sys
- import threading
- from routes import request_config
- from routes.lru import LRUCache
- from routes.util import controller_scan, MatchException, RoutesException
- from routes.route import Route
- COLLECTION_ACTIONS = [
- 'index',
- 'create',
- 'new']
- MEMBER_ACTIONS = [
- 'show',
- 'update',
- 'delete',
- 'edit']
-
- def strip_slashes(name):
- if name.startswith('/'):
- name = name[1:]
-
- if name.endswith('/'):
- name = name[:-1]
-
- return name
-
-
- class SubMapperParent(object):
-
- def submapper(self, **kargs):
- return SubMapper(self, **kargs)
-
-
- def collection(self, collection_name, resource_name, path_prefix = None, member_prefix = '/{id}', controller = None, collection_actions = COLLECTION_ACTIONS, member_actions = MEMBER_ACTIONS, member_options = None, **kwargs):
- if controller is None:
- if not resource_name:
- pass
- controller = collection_name
-
- if path_prefix is None:
- path_prefix = '/' + collection_name
-
- collection = SubMapper(self, collection_name = collection_name, resource_name = resource_name, path_prefix = path_prefix, controller = controller, actions = collection_actions, **kwargs)
- if not member_options:
- pass
- collection.member = SubMapper(collection, path_prefix = member_prefix, actions = member_actions, **{ })
- return collection
-
-
-
- class SubMapper(SubMapperParent):
-
- def __init__(self, obj, resource_name = None, collection_name = None, actions = None, formatted = None, **kwargs):
- self.kwargs = kwargs
- self.obj = obj
- self.collection_name = collection_name
- self.member = None
- if not resource_name and getattr(obj, 'resource_name', None) and kwargs.get('controller', None):
- pass
- self.resource_name = getattr(obj, 'controller', None)
- if formatted is not None:
- self.formatted = formatted
- else:
- self.formatted = getattr(obj, 'formatted', None)
- if self.formatted is None:
- self.formatted = True
-
- if not actions:
- pass
- self.add_actions([])
-
-
- def connect(self, *args, **kwargs):
- newkargs = { }
- newargs = args
- for key, value in self.kwargs.items():
- if key == 'path_prefix':
- if len(args) > 1:
- newargs = (args[0], self.kwargs[key] + args[1])
- else:
- newargs = (self.kwargs[key] + args[0],)
- len(args) > 1
- if key in kwargs:
- if isinstance(value, dict):
- newkargs[key] = dict(value, **kwargs[key])
- else:
- newkargs[key] = value + kwargs[key]
- isinstance(value, dict)
- newkargs[key] = self.kwargs[key]
-
- for key in kwargs:
- if key not in self.kwargs:
- newkargs[key] = kwargs[key]
- continue
-
- return self.obj.connect(*newargs, **newkargs)
-
-
- def link(self, rel = None, name = None, action = None, method = 'GET', formatted = None, **kwargs):
- if (formatted or formatted is None) and self.formatted:
- suffix = '{.format}'
- else:
- suffix = ''
- if not name:
- pass
- if not rel:
- pass
- if not action and rel:
- pass
- return self.connect(rel + '_' + self.resource_name, '/' + name + suffix, action = name, **_kwargs_with_conditions(kwargs, method))
-
-
- def new(self, **kwargs):
- return self.link(rel = 'new', **kwargs)
-
-
- def edit(self, **kwargs):
- return self.link(rel = 'edit', **kwargs)
-
-
- def action(self, name = None, action = None, method = 'GET', formatted = None, **kwargs):
- if (formatted or formatted is None) and self.formatted:
- suffix = '{.format}'
- else:
- suffix = ''
- if not name:
- pass
- if not action:
- pass
- return self.connect(action + '_' + self.resource_name, suffix, action = name, **_kwargs_with_conditions(kwargs, method))
-
-
- def index(self, name = None, **kwargs):
- if not name:
- pass
- return self.action(name = self.collection_name, action = 'index', method = 'GET', **kwargs)
-
-
- def show(self, name = None, **kwargs):
- if not name:
- pass
- return self.action(name = self.resource_name, action = 'show', method = 'GET', **kwargs)
-
-
- def create(self, **kwargs):
- return self.action(action = 'create', method = 'POST', **kwargs)
-
-
- def update(self, **kwargs):
- return self.action(action = 'update', method = 'PUT', **kwargs)
-
-
- def delete(self, **kwargs):
- return self.action(action = 'delete', method = 'DELETE', **kwargs)
-
-
- def add_actions(self, actions):
- [ getattr(self, action)() for action in actions ]
-
-
- def __enter__(self):
- return self
-
-
- def __exit__(self, type, value, tb):
- pass
-
-
-
- def _kwargs_with_conditions(kwargs, method):
- if method and 'conditions' not in kwargs:
- newkwargs = kwargs.copy()
- newkwargs['conditions'] = {
- 'method': method }
- return newkwargs
- return kwargs
-
-
- class Mapper(SubMapperParent):
-
- def __init__(self, controller_scan = controller_scan, directory = None, always_scan = False, register = True, explicit = True):
- self.matchlist = []
- self.maxkeys = { }
- self.minkeys = { }
- self.urlcache = LRUCache(1600)
- self._created_regs = False
- self._created_gens = False
- self._master_regexp = None
- self.prefix = None
- self.req_data = threading.local()
- self.directory = directory
- self.always_scan = always_scan
- self.controller_scan = controller_scan
- self._regprefix = None
- self._routenames = { }
- self.debug = False
- self.append_slash = False
- self.sub_domains = False
- self.sub_domains_ignore = []
- self.domain_match = '[^\\.\\/]+?\\.[^\\.\\/]+'
- self.explicit = explicit
- self.encoding = 'utf-8'
- self.decode_errors = 'ignore'
- self.hardcode_names = True
- self.minimization = False
- self.create_regs_lock = threading.Lock()
- if register:
- config = request_config()
- config.mapper = self
-
-
-
- def __str__(self):
-
- def format_methods(r):
- if r.conditions:
- method = r.conditions.get('method', '')
- if not type(method) is str or method:
- pass
- return ', '.join(method)
- return ''
-
- table = [] + [ ('', format_methods(r), '') for r in self.matchlist ]
- widths = [ (max,)((lambda .0: for row in .0:
- len(row[col]))(table)) for None in range(len(table[0])) ]
- return ('\n'.join,)((lambda .0: for None in .0:
- row = None(None, ' '.join)((lambda .0: for col in .0:
- row[col].ljust(widths[col]))(range(len(widths))))
-
- )(table))
-
-
- def _envget(self):
-
- try:
- return self.req_data.environ
- except AttributeError:
- return None
-
-
-
- def _envset(self, env):
- self.req_data.environ = env
-
-
- def _envdel(self):
- del self.req_data.environ
-
- environ = property(_envget, _envset, _envdel)
-
- def extend(self, routes, path_prefix = ''):
- for route in routes:
- if path_prefix and route.minimization:
- routepath = '/'.join([
- path_prefix,
- route.routepath])
- elif path_prefix:
- routepath = path_prefix + route.routepath
- else:
- routepath = route.routepath
- self.connect(route.name, routepath, **route._kargs)
-
-
-
- def connect(self, *args, **kargs):
- routename = None
- if len(args) > 1:
- routename = args[0]
- else:
- args = (None,) + args
- if '_explicit' not in kargs:
- kargs['_explicit'] = self.explicit
-
- if '_minimize' not in kargs:
- kargs['_minimize'] = self.minimization
-
- route = Route(*args, **kargs)
- if (self.encoding != 'utf-8' or self.decode_errors != 'ignore') and '_encoding' not in kargs:
- route.encoding = self.encoding
- route.decode_errors = self.decode_errors
-
- if not route.static:
- self.matchlist.append(route)
-
- if routename:
- self._routenames[routename] = route
- route.name = routename
-
- if route.static:
- return None
- exists = False
- for key in self.maxkeys:
- if key == route.maxkeys:
- self.maxkeys[key].append(route)
- exists = True
- break
- continue
- route.static
-
- if not exists:
- self.maxkeys[route.maxkeys] = [
- route]
-
- self._created_gens = False
-
-
- def _create_gens(self):
- controllerlist = { }
- actionlist = { }
- for route in self.matchlist:
- if route.static:
- continue
-
- if route.defaults.has_key('controller'):
- controllerlist[route.defaults['controller']] = True
-
- if route.defaults.has_key('action'):
- actionlist[route.defaults['action']] = True
- continue
-
- controllerlist = controllerlist.keys() + [
- '*']
- actionlist = actionlist.keys() + [
- '*']
- gendict = { }
- for route in self.matchlist:
- if route.static:
- continue
-
- clist = controllerlist
- alist = actionlist
- if 'controller' in route.hardcoded:
- clist = [
- route.defaults['controller']]
-
- if 'action' in route.hardcoded:
- alist = [
- unicode(route.defaults['action'])]
-
- for controller in clist:
- for action in alist:
- actiondict = gendict.setdefault(controller, { })
- actiondict.setdefault(action, ([], { }))[0].append(route)
-
-
-
- self._gendict = gendict
- self._created_gens = True
-
-
- def create_regs(self, *args, **kwargs):
- self.create_regs_lock.acquire()
-
- try:
- self._create_regs(*args, **kwargs)
- finally:
- self.create_regs_lock.release()
-
-
-
- def _create_regs(self, clist = None):
- if clist is None:
- if self.directory:
- clist = self.controller_scan(self.directory)
- elif callable(self.controller_scan):
- clist = self.controller_scan()
- elif not self.controller_scan:
- clist = []
- else:
- clist = self.controller_scan
-
- for key, val in self.maxkeys.iteritems():
- for route in val:
- route.makeregexp(clist)
-
-
- regexps = []
- routematches = []
- for route in self.matchlist:
- if not route.static:
- routematches.append(route)
- regexps.append(route.makeregexp(clist, include_names = False))
- continue
-
- self._routematches = routematches
- if self.prefix:
- self._regprefix = re.compile(self.prefix + '(.*)')
-
- regexp = []([ '(?:%s)' % x for x in regexps ])
- self._master_reg = regexp
- self._master_regexp = re.compile(regexp)
- self._created_regs = True
-
-
- def _match(self, url, environ):
- if not (self._created_regs) and self.controller_scan:
- self.create_regs()
- elif not self._created_regs:
- raise RoutesException('You must generate the regular expressions before matching.')
-
- if self.always_scan:
- self.create_regs()
-
- matchlog = []
- if self.prefix:
- if re.match(self._regprefix, url):
- url = re.sub(self._regprefix, '\\1', url)
- if not url:
- url = '/'
-
- else:
- return (None, None, matchlog)
- re.match(self._regprefix, url)
- if not environ:
- pass
- environ = self.environ
- sub_domains = self.sub_domains
- sub_domains_ignore = self.sub_domains_ignore
- domain_match = self.domain_match
- debug = self.debug
- valid_url = re.match(self._master_regexp, url)
- if not valid_url:
- return (None, None, matchlog)
- for route in self.matchlist:
- match = route.match(url, environ, sub_domains, sub_domains_ignore, domain_match)
- if debug:
- matchlog.append(dict(route = route, regexp = bool(match)))
-
- if isinstance(match, dict) or match:
- return (match, route, matchlog)
-
- return (None, None, matchlog)
-
-
- def match(self, url = None, environ = None):
- if not url and not environ:
- raise RoutesException('URL or environ must be provided')
- not environ
- if not url:
- url = environ['PATH_INFO']
-
- result = self._match(url, environ)
- if self.debug:
- return (result[0], result[1], result[2])
- if isinstance(result[0], dict) or result[0]:
- return result[0]
-
-
- def routematch(self, url = None, environ = None):
- if not url and not environ:
- raise RoutesException('URL or environ must be provided')
- not environ
- if not url:
- url = environ['PATH_INFO']
-
- result = self._match(url, environ)
- if self.debug:
- return (result[0], result[1], result[2])
- if isinstance(result[0], dict) or result[0]:
- return (result[0], result[1])
-
-
- def generate(self, *args, **kargs):
- if not self._created_gens:
- self._create_gens()
-
- if self.append_slash:
- kargs['_append_slash'] = True
-
- if not self.explicit:
- if 'controller' not in kargs:
- kargs['controller'] = 'content'
-
- if 'action' not in kargs:
- kargs['action'] = 'index'
-
-
- controller = kargs.get('controller', None)
- action = kargs.get('action', None)
- cache_key = unicode(args).encode('utf8') + unicode(kargs).encode('utf8')
- if self.urlcache is not None:
- if self.environ:
- cache_key_script_name = '%s:%s' % (self.environ.get('SCRIPT_NAME', ''), cache_key)
- else:
- cache_key_script_name = cache_key
- for key in [
- cache_key,
- cache_key_script_name]:
- if key in self.urlcache:
- return self.urlcache[key]
-
-
- if not self._gendict.get(controller):
- pass
- actionlist = self._gendict.get('*', { })
- if not actionlist and not args:
- return None
- if not actionlist.get(action):
- pass
- (keylist, sortcache) = actionlist.get('*', (None, { }))
- if not keylist and not args:
- return None
- keys = frozenset(kargs.keys())
- cacheset = False
- cachekey = unicode(keys)
- cachelist = sortcache.get(cachekey)
- if args:
- keylist = args
- elif cachelist:
- keylist = cachelist
- else:
- cacheset = True
- newlist = []
- for route in keylist:
- if len(route.minkeys - route.dotkeys - keys) == 0:
- newlist.append(route)
- continue
-
- keylist = newlist
-
- def keysort(a, b):
- am = a.minkeys
- a = a.maxkeys
- b = b.maxkeys
- lendiffa = len(keys ^ a)
- lendiffb = len(keys ^ b)
- if lendiffa == 0 and lendiffb == 0:
- return 0
- if lendiffa == 0:
- return -1
- if lendiffb == 0:
- return 1
- if cmp(lendiffa, lendiffb) != 0:
- return cmp(lendiffa, lendiffb)
- if len(keys & b) == len(keys & a):
- return cmp(len(a), len(b))
- return cmp(len(keys & b), len(keys & a))
-
- keylist.sort(keysort)
- if cacheset:
- sortcache[cachekey] = keylist
-
- for route in keylist:
- fail = False
- for key in route.hardcoded:
- kval = kargs.get(key)
- if not kval:
- continue
-
- if isinstance(kval, str):
- kval = kval.decode(self.encoding)
- else:
- kval = unicode(kval)
- if kval != route.defaults[key] and not callable(route.defaults[key]):
- fail = True
- break
- continue
-
- if fail:
- continue
-
- path = route.generate(**kargs)
- if path:
- if self.prefix:
- path = self.prefix + path
-
- if route.static:
- pass
- external_static = route.external
- if self.environ and self.environ.get('SCRIPT_NAME', '') != '' and not (route.absolute) and not external_static:
- path = self.environ['SCRIPT_NAME'] + path
- key = cache_key_script_name
- else:
- key = cache_key
- if self.urlcache is not None:
- self.urlcache[key] = str(path)
-
- return str(path)
-
-
-
- def resource(self, member_name, collection_name, **kwargs):
- collection = kwargs.pop('collection', { })
- member = kwargs.pop('member', { })
- new = kwargs.pop('new', { })
- path_prefix = kwargs.pop('path_prefix', None)
- name_prefix = kwargs.pop('name_prefix', None)
- parent_resource = kwargs.pop('parent_resource', None)
- if parent_resource is not None:
- if path_prefix is None:
- path_prefix = '%s/:%s_id' % (parent_resource['collection_name'], parent_resource['member_name'])
-
- if name_prefix is None:
- name_prefix = '%s_' % parent_resource['member_name']
-
- elif path_prefix is None:
- path_prefix = ''
-
- if name_prefix is None:
- name_prefix = ''
-
- member['edit'] = 'GET'
- new.update({
- 'new': 'GET' })
-
- def swap(dct, newdct):
- for key, val in dct.iteritems():
- newdct.setdefault(val.upper(), []).append(key)
-
- return newdct
-
- collection_methods = swap(collection, { })
- member_methods = swap(member, { })
- new_methods = swap(new, { })
- collection_methods.setdefault('POST', []).insert(0, 'create')
- member_methods.setdefault('PUT', []).insert(0, 'update')
- member_methods.setdefault('DELETE', []).insert(0, 'delete')
- controller = strip_slashes(collection_name)
- path_prefix = strip_slashes(path_prefix)
- path_prefix = '/' + path_prefix
- if path_prefix and path_prefix != '/':
- path = path_prefix + '/' + controller
- else:
- path = '/' + controller
- collection_path = path
- new_path = path + '/new'
- member_path = path + '/:(id)'
- options = {
- 'controller': kwargs.get('controller', controller),
- '_member_name': member_name,
- '_collection_name': collection_name,
- '_parent_resource': parent_resource,
- '_filter': kwargs.get('_filter') }
-
- def requirements_for(meth):
- opts = options.copy()
- if method != 'any':
- opts['conditions'] = {
- 'method': [
- meth.upper()] }
-
- return opts
-
- for method, lst in collection_methods.iteritems():
- if not method != 'GET' or lst.pop(0):
- pass
- primary = None
- route_options = requirements_for(method)
- for action in lst:
- route_options['action'] = action
- route_name = '%s%s_%s' % (name_prefix, action, collection_name)
- self.connect('formatted_' + route_name, '%s/%s.:(format)' % (collection_path, action), **route_options)
- self.connect(route_name, '%s/%s' % (collection_path, action), **route_options)
-
- if primary:
- route_options['action'] = primary
- self.connect('%s.:(format)' % collection_path, **route_options)
- self.connect(collection_path, **route_options)
- continue
- (None, None)
-
- self.connect('formatted_' + name_prefix + collection_name, collection_path + '.:(format)', action = 'index', conditions = {
- 'method': [
- 'GET'] }, **options)
- self.connect(name_prefix + collection_name, collection_path, action = 'index', conditions = {
- 'method': [
- 'GET'] }, **options)
- for method, lst in new_methods.iteritems():
- route_options = requirements_for(method)
- for action in lst:
- if not action == 'new' or new_path:
- pass
- path = '%s/%s' % (new_path, action)
- name = 'new_' + member_name
- if action != 'new':
- name = action + '_' + name
-
- route_options['action'] = action
- if not action == 'new' or new_path + '.:(format)':
- pass
- formatted_path = '%s/%s.:(format)' % (new_path, action)
- self.connect('formatted_' + name_prefix + name, formatted_path, **route_options)
- self.connect(name_prefix + name, path, **route_options)
-
-
- requirements_regexp = '[^\\/]+'
- for method, lst in member_methods.iteritems():
- route_options = requirements_for(method)
- route_options['requirements'] = {
- 'id': requirements_regexp }
- if method not in ('POST', 'GET', 'any'):
- primary = lst.pop(0)
- else:
- primary = None
- for action in lst:
- route_options['action'] = action
- self.connect('formatted_%s%s_%s' % (name_prefix, action, member_name), '%s/%s.:(format)' % (member_path, action), **route_options)
- self.connect('%s%s_%s' % (name_prefix, action, member_name), '%s/%s' % (member_path, action), **route_options)
-
- if primary:
- route_options['action'] = primary
- self.connect('%s.:(format)' % member_path, **route_options)
- self.connect(member_path, **route_options)
- continue
-
- route_options = requirements_for('GET')
- route_options['action'] = 'show'
- route_options['requirements'] = {
- 'id': requirements_regexp }
- self.connect('formatted_' + name_prefix + member_name, member_path + '.:(format)', **route_options)
- self.connect(name_prefix + member_name, member_path, **route_options)
-
-
- def redirect(self, match_path, destination_path, *args, **kwargs):
- both_args = [
- '_encoding',
- '_explicit',
- '_minimize']
- gen_args = [
- '_filter']
- status_code = kwargs.pop('_redirect_code', '302 Found')
- gen_dict = { }
- match_dict = { }
- for key in both_args + gen_args:
- if key in kwargs:
- gen_dict[key] = kwargs[key]
- continue
-
- gen_dict['_static'] = True
- for key in kwargs:
- if key not in gen_args:
- match_dict[key] = kwargs[key]
- continue
-
- self.connect(match_path, **match_dict)
- match_route = self.matchlist[-1]
- self.connect('_redirect_%s' % id(match_route), destination_path, **gen_dict)
- match_route.redirect = True
- match_route.redirect_status = status_code
-
-
-