home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_2391 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  9.9 KB  |  391 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import os
  5. import re
  6. import urllib
  7. from routes import request_config
  8.  
  9. class RoutesException(Exception):
  10.     pass
  11.  
  12.  
  13. class MatchException(RoutesException):
  14.     pass
  15.  
  16.  
  17. class GenerationException(RoutesException):
  18.     pass
  19.  
  20.  
  21. def _screenargs(kargs, mapper, environ, force_explicit = False):
  22.     encoding = mapper.encoding
  23.     for key, val in kargs.iteritems():
  24.         if isinstance(val, unicode):
  25.             kargs[key] = val.encode(encoding)
  26.             continue
  27.     
  28.     if mapper.explicit and mapper.sub_domains and not force_explicit:
  29.         return _subdomain_check(kargs, mapper, environ)
  30.     if mapper.explicit and not force_explicit:
  31.         return kargs
  32.     controller_name = kargs.get('controller')
  33.     if controller_name and controller_name.startswith('/'):
  34.         kargs['controller'] = kargs['controller'][1:]
  35.         return kargs
  36.     route_args = environ.get('wsgiorg.routing_args')
  37.     if route_args:
  38.         memory_kargs = route_args[1].copy()
  39.     else:
  40.         memory_kargs = { }
  41.     for key in kargs.keys():
  42.         if kargs[key] is None:
  43.             continue
  44.         _[1][key]
  45.     
  46.     memory_kargs.update(kargs)
  47.     if mapper.sub_domains:
  48.         memory_kargs = _subdomain_check(memory_kargs, mapper, environ)
  49.     
  50.     return memory_kargs
  51.  
  52.  
  53. def _subdomain_check(kargs, mapper, environ):
  54.     if mapper.sub_domains:
  55.         subdomain = kargs.pop('sub_domain', None)
  56.         if isinstance(subdomain, unicode):
  57.             subdomain = str(subdomain)
  58.         
  59.         if not environ.get('HTTP_HOST'):
  60.             pass
  61.         fullhost = environ.get('SERVER_NAME')
  62.         if not fullhost:
  63.             return kargs
  64.         hostmatch = fullhost.split(':')
  65.         host = hostmatch[0]
  66.         port = ''
  67.         if len(hostmatch) > 1:
  68.             port += ':' + hostmatch[1]
  69.         
  70.         sub_match = re.compile('^.+?\\.(%s)$' % mapper.domain_match)
  71.         domain = re.sub(sub_match, '\\1', host)
  72.         if subdomain and not host.startswith(subdomain) and subdomain not in mapper.sub_domains_ignore:
  73.             kargs['_host'] = subdomain + '.' + domain + port
  74.         elif (subdomain in mapper.sub_domains_ignore or subdomain is None) and domain != host:
  75.             kargs['_host'] = domain + port
  76.         
  77.         return kargs
  78.     return kargs
  79.  
  80.  
  81. def _url_quote(string, encoding):
  82.     if encoding:
  83.         if isinstance(string, unicode):
  84.             s = string.encode(encoding)
  85.         elif isinstance(string, str):
  86.             s = string
  87.         else:
  88.             s = unicode(string).encode(encoding)
  89.     else:
  90.         s = str(string)
  91.     return urllib.quote(s, '/')
  92.  
  93.  
  94. def _str_encode(string, encoding):
  95.     if encoding:
  96.         if isinstance(string, unicode):
  97.             s = string.encode(encoding)
  98.         elif isinstance(string, str):
  99.             s = string
  100.         else:
  101.             s = unicode(string).encode(encoding)
  102.     
  103.     return s
  104.  
  105.  
  106. def url_for(*args, **kargs):
  107.     anchor = kargs.get('anchor')
  108.     host = kargs.get('host')
  109.     protocol = kargs.get('protocol')
  110.     qualified = kargs.pop('qualified', None)
  111.     for key in [
  112.         'anchor',
  113.         'host',
  114.         'protocol']:
  115.         if kargs.get(key):
  116.             del kargs[key]
  117.             continue
  118.     
  119.     config = request_config()
  120.     route = None
  121.     static = False
  122.     encoding = config.mapper.encoding
  123.     url = ''
  124.     if len(args) > 0:
  125.         route = config.mapper._routenames.get(args[0])
  126.         if not route:
  127.             static = True
  128.             url = args[0]
  129.         
  130.         if url.startswith('/') and hasattr(config, 'environ') and config.environ.get('SCRIPT_NAME'):
  131.             url = config.environ.get('SCRIPT_NAME') + url
  132.         
  133.         if static:
  134.             if kargs:
  135.                 url += '?'
  136.                 query_args = []
  137.                 for key, val in kargs.iteritems():
  138.                     if isinstance(val, (list, tuple)):
  139.                         for value in val:
  140.                             query_args.append('%s=%s' % (urllib.quote(unicode(key).encode(encoding)), urllib.quote(unicode(value).encode(encoding))))
  141.                         
  142.                     query_args.append('%s=%s' % (urllib.quote(unicode(key).encode(encoding)), urllib.quote(unicode(val).encode(encoding))))
  143.                 
  144.                 url += '&'.join(query_args)
  145.             
  146.         
  147.     
  148.     environ = getattr(config, 'environ', { })
  149.     if 'wsgiorg.routing_args' not in environ:
  150.         environ = environ.copy()
  151.         mapper_dict = getattr(config, 'mapper_dict', None)
  152.         if mapper_dict is not None:
  153.             match_dict = mapper_dict.copy()
  154.         else:
  155.             match_dict = { }
  156.         environ['wsgiorg.routing_args'] = ((), match_dict)
  157.     
  158.     if not static:
  159.         route_args = []
  160.         if route:
  161.             if config.mapper.hardcode_names:
  162.                 route_args.append(route)
  163.             
  164.             newargs = route.defaults.copy()
  165.             newargs.update(kargs)
  166.             if route.filter:
  167.                 newargs = route.filter(newargs)
  168.             
  169.             if not route.static:
  170.                 newargs = _subdomain_check(newargs, config.mapper, environ)
  171.             
  172.         else:
  173.             newargs = _screenargs(kargs, config.mapper, environ)
  174.         if not newargs.pop('_anchor', None):
  175.             pass
  176.         anchor = anchor
  177.         if not newargs.pop('_host', None):
  178.             pass
  179.         host = host
  180.         if not newargs.pop('_protocol', None):
  181.             pass
  182.         protocol = protocol
  183.         url = config.mapper.generate(*route_args, **newargs)
  184.     
  185.     if anchor is not None:
  186.         url += '#' + _url_quote(anchor, encoding)
  187.     
  188.     if host and protocol or qualified:
  189.         if not host and not qualified:
  190.             host = config.host.split(':')[0]
  191.         elif not host:
  192.             host = config.host
  193.         
  194.         if not protocol:
  195.             protocol = config.protocol
  196.         
  197.         if url is not None:
  198.             url = protocol + '://' + host + url
  199.         
  200.     
  201.     if not isinstance(url, str) and url is not None:
  202.         raise GenerationException('url_for can only return a string, got unicode instead: %s' % url)
  203.     url is not None
  204.     if url is None:
  205.         raise GenerationException('url_for could not generate URL. Called with args: %s %s' % (args, kargs))
  206.     url is None
  207.     return url
  208.  
  209.  
  210. class URLGenerator(object):
  211.     
  212.     def __init__(self, mapper, environ):
  213.         self.mapper = mapper
  214.         if 'SCRIPT_NAME' not in environ:
  215.             environ['SCRIPT_NAME'] = ''
  216.         
  217.         self.environ = environ
  218.  
  219.     
  220.     def __call__(self, *args, **kargs):
  221.         anchor = kargs.get('anchor')
  222.         host = kargs.get('host')
  223.         protocol = kargs.get('protocol')
  224.         qualified = kargs.pop('qualified', None)
  225.         for key in [
  226.             'anchor',
  227.             'host',
  228.             'protocol']:
  229.             if kargs.get(key):
  230.                 del kargs[key]
  231.                 continue
  232.         
  233.         route = None
  234.         if '_use_current' in kargs:
  235.             pass
  236.         use_current = kargs.pop('_use_current')
  237.         static = False
  238.         encoding = self.mapper.encoding
  239.         url = ''
  240.         more_args = len(args) > 0
  241.         if more_args:
  242.             route = self.mapper._routenames.get(args[0])
  243.         
  244.         if not route and more_args:
  245.             static = True
  246.             url = args[0]
  247.             if url.startswith('/') and self.environ.get('SCRIPT_NAME'):
  248.                 url = self.environ.get('SCRIPT_NAME') + url
  249.             
  250.             if static:
  251.                 if kargs:
  252.                     url += '?'
  253.                     query_args = []
  254.                     for key, val in kargs.iteritems():
  255.                         if isinstance(val, (list, tuple)):
  256.                             for value in val:
  257.                                 query_args.append('%s=%s' % (urllib.quote(unicode(key).encode(encoding)), urllib.quote(unicode(value).encode(encoding))))
  258.                             
  259.                         query_args.append('%s=%s' % (urllib.quote(unicode(key).encode(encoding)), urllib.quote(unicode(val).encode(encoding))))
  260.                     
  261.                     url += '&'.join(query_args)
  262.                 
  263.             
  264.         
  265.         if not static:
  266.             route_args = []
  267.             if route:
  268.                 if self.mapper.hardcode_names:
  269.                     route_args.append(route)
  270.                 
  271.                 newargs = route.defaults.copy()
  272.                 newargs.update(kargs)
  273.                 if route.filter:
  274.                     newargs = route.filter(newargs)
  275.                 
  276.                 if (not (route.static) or route.static) and not (route.external):
  277.                     sub = newargs.get('sub_domain', None)
  278.                     newargs = _subdomain_check(newargs, self.mapper, self.environ)
  279.                     if 'sub_domain' in route.defaults:
  280.                         newargs['sub_domain'] = sub
  281.                     
  282.                 
  283.             elif use_current:
  284.                 newargs = _screenargs(kargs, self.mapper, self.environ, force_explicit = True)
  285.             elif 'sub_domain' in kargs:
  286.                 newargs = _subdomain_check(kargs, self.mapper, self.environ)
  287.             else:
  288.                 newargs = kargs
  289.             if not anchor:
  290.                 pass
  291.             anchor = newargs.pop('_anchor', None)
  292.             if not host:
  293.                 pass
  294.             host = newargs.pop('_host', None)
  295.             if not protocol:
  296.                 pass
  297.             protocol = newargs.pop('_protocol', None)
  298.             url = self.mapper.generate(*route_args, **newargs)
  299.         
  300.         if anchor is not None:
  301.             url += '#' + _url_quote(anchor, encoding)
  302.         
  303.         if host and protocol or qualified:
  304.             if 'routes.cached_hostinfo' not in self.environ:
  305.                 cache_hostinfo(self.environ)
  306.             
  307.             hostinfo = self.environ['routes.cached_hostinfo']
  308.             if not host and not qualified:
  309.                 host = hostinfo['host'].split(':')[0]
  310.             elif not host:
  311.                 host = hostinfo['host']
  312.             
  313.             if not protocol:
  314.                 protocol = hostinfo['protocol']
  315.             
  316.             if url is not None:
  317.                 if host[-1] != '/':
  318.                     host += '/'
  319.                 
  320.                 url = protocol + '://' + host + url.lstrip('/')
  321.             
  322.         
  323.         if not isinstance(url, str) and url is not None:
  324.             raise GenerationException('Can only return a string, got unicode instead: %s' % url)
  325.         url is not None
  326.         if url is None:
  327.             raise GenerationException('Could not generate URL. Called with args: %s %s' % (args, kargs))
  328.         url is None
  329.         return url
  330.  
  331.     
  332.     def current(self, *args, **kwargs):
  333.         return self(_use_current = True, *args, **kwargs)
  334.  
  335.  
  336.  
  337. def redirect_to(*args, **kargs):
  338.     target = url_for(*args, **kargs)
  339.     config = request_config()
  340.     return config.redirect(target)
  341.  
  342.  
  343. def cache_hostinfo(environ):
  344.     hostinfo = { }
  345.     if environ.get('HTTPS') and environ.get('wsgi.url_scheme') == 'https' or environ.get('HTTP_X_FORWARDED_PROTO') == 'https':
  346.         hostinfo['protocol'] = 'https'
  347.     else:
  348.         hostinfo['protocol'] = 'http'
  349.     if environ.get('HTTP_X_FORWARDED_HOST'):
  350.         hostinfo['host'] = environ['HTTP_X_FORWARDED_HOST']
  351.     elif environ.get('HTTP_HOST'):
  352.         hostinfo['host'] = environ['HTTP_HOST']
  353.     else:
  354.         hostinfo['host'] = environ['SERVER_NAME']
  355.         if environ.get('wsgi.url_scheme') == 'https':
  356.             if environ['SERVER_PORT'] != '443':
  357.                 hostinfo['host'] += ':' + environ['SERVER_PORT']
  358.             
  359.         elif environ['SERVER_PORT'] != '80':
  360.             hostinfo['host'] += ':' + environ['SERVER_PORT']
  361.         
  362.     environ['routes.cached_hostinfo'] = hostinfo
  363.     return hostinfo
  364.  
  365.  
  366. def controller_scan(directory = None):
  367.     if directory is None:
  368.         return []
  369.     
  370.     def find_controllers(dirname, prefix = ('',)):
  371.         controllers = []
  372.         for fname in os.listdir(dirname):
  373.             filename = os.path.join(dirname, fname)
  374.             if os.path.isfile(filename) and re.match('^[^_]{1,1}.*\\.py$', fname):
  375.                 controllers.append(prefix + fname[:-3])
  376.                 continue
  377.             if os.path.isdir(filename):
  378.                 controllers.extend(find_controllers(filename, prefix = prefix + fname + '/'))
  379.                 continue
  380.         
  381.         return controllers
  382.  
  383.     
  384.     def longest_first(fst, lst):
  385.         return cmp(len(lst), len(fst))
  386.  
  387.     controllers = find_controllers(directory)
  388.     controllers.sort(longest_first)
  389.     return controllers
  390.  
  391.