Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

Changeset 807

Show
Ignore:
Timestamp:
11/10/05 12:41:40
Author:
fumanchu
Message:

Moved filter-handling code into lib.filter.init.py. Also moved unrepr and modules(), attributes() functions into cptools.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/cherrypy/_cphttptools.py

    r806 r807  
    88import cherrypy 
    99from cherrypy import _cputil, _cpcgifs, _cpwsgiserver 
     10from cherrypy.lib.filter import applyFilters 
    1011from cherrypy.lib import cptools, httptools 
    1112 
     
    442443            for y in flattener(x): 
    443444                yield y  
    444  
    445 def applyFilters(methodName): 
    446     """Execute the given method for all registered filters.""" 
    447     if methodName in ('onStartResource', 'beforeRequestBody', 'beforeMain'): 
    448         filterList = (_cputil._cpDefaultInputFilterList + 
    449                       _cputil.getSpecialAttribute('_cpFilterList')) 
    450     elif methodName in ('beforeFinalize', 'onEndResource', 
    451                 'beforeErrorResponse', 'afterErrorResponse'): 
    452         filterList = (_cputil.getSpecialAttribute('_cpFilterList') + 
    453                       _cputil._cpDefaultOutputFilterList) 
    454     else: 
    455         assert False # Wrong methodName for the filter 
    456     for filter in filterList: 
    457         method = getattr(filter, methodName, None) 
    458         if method: 
    459             method() 
  • trunk/cherrypy/_cpserver.py

    r779 r807  
    88import cherrypy 
    99from cherrypy import _cphttptools 
    10 from cherrypy.lib import autoreload, profiler 
     10from cherrypy.lib import autoreload, profiler, filter, cptools 
    1111 
    1212# Use a flag to indicate the state of the application server. 
     
    5353        elif serverClass and isinstance(serverClass, basestring): 
    5454            # Dynamically load the class from the given string 
    55             serverClass = cherrypy._cputil.attributes(serverClass) 
     55            serverClass = cptools.attributes(serverClass) 
    5656         
    5757        self.blocking = not initOnly 
     
    278278     
    279279    # Initialize the built in filters 
    280     cherrypy._cputil._cpInitDefaultFilters() 
    281     cherrypy._cputil._cpInitUserDefinedFilters() 
     280    filter.init() 
    282281 
    283282 
  • trunk/cherrypy/_cputil.py

    r806 r807  
    308308    cherrypy.HTTPError(500).set_response() 
    309309 
     310 
    310311_cpFilterList = [] 
    311312 
    312 # Filters that are always included 
    313 from cherrypy.lib.filter import baseurlfilter, cachefilter, \ 
    314     decodingfilter, encodingfilter, gzipfilter, logdebuginfofilter, \ 
    315     staticfilter, nsgmlsfilter, tidyfilter, \ 
    316     xmlrpcfilter, sessionauthenticatefilter, \ 
    317     sessionfilter 
    318  
    319 # this contains the classes for each filter type 
    320 # we do not store the instances here because the test 
    321 # suite must reinitilize the filters without restarting 
    322 # the server 
    323 _cpDefaultFilterClasses = { 
    324     'BaseUrlFilter'      : baseurlfilter.BaseUrlFilter, 
    325     'CacheFilter'        : cachefilter.CacheFilter, 
    326     'DecodingFilter'     : decodingfilter.DecodingFilter, 
    327     'EncodingFilter'     : encodingfilter.EncodingFilter, 
    328     'GzipFilter'         : gzipfilter.GzipFilter, 
    329     'LogDebugInfoFilter' : logdebuginfofilter.LogDebugInfoFilter, 
    330     'NsgmlsFilter'       : nsgmlsfilter.NsgmlsFilter, 
    331     'SessionAuthenticateFilter' : sessionauthenticatefilter.SessionAuthenticateFilter, 
    332     'SessionFilter'      : sessionfilter.SessionFilter, 
    333     'StaticFilter'       : staticfilter.StaticFilter, 
    334     'TidyFilter'         : tidyfilter.TidyFilter, 
    335     'XmlRpcFilter'       : xmlrpcfilter.XmlRpcFilter, 
    336 } 
    337  
    338 # this is where the actual filter instances are first stored 
    339 _cpDefaultFilterInstances = {} 
    340  
    341 # These are in order for a reason! 
    342 # They must be strings matching keys in _cpDefaultFilterClasses 
    343 __cpDefaultInputFilterNames = [ 
    344     'CacheFilter', 
    345     'LogDebugInfoFilter', 
    346     'BaseUrlFilter', 
    347     'DecodingFilter', 
    348     'SessionFilter', 
    349     'SessionAuthenticateFilter', 
    350     'StaticFilter', 
    351     'NsgmlsFilter', 
    352     'TidyFilter', 
    353     'XmlRpcFilter', 
    354 ] 
    355  
    356 __cpDefaultOutputFilterNames = [ 
    357     'XmlRpcFilter', 
    358     'EncodingFilter', 
    359     'TidyFilter', 
    360     'NsgmlsFilter', 
    361     'LogDebugInfoFilter', 
    362     'GzipFilter', 
    363     'SessionFilter', 
    364     'CacheFilter', 
    365 ] 
    366  
    367 # these are the lists cp internally uses to access the filters 
    368 # they are populated when _cpInitDefaultFilters is called 
    369 _cpDefaultInputFilterList  = [] 
    370 _cpDefaultOutputFilterList = [] 
    371  
    372 # initilize the default filters 
    373 def _cpInitDefaultFilters(): 
    374     global _cpDefaultInputFilterList, _cpDefaultOutputFilterList 
    375     global _cpDefaultFilterInstances 
    376     _cpDefaultInputFilterList  = [] 
    377     _cpDefaultOutputFilterList = [] 
    378     _cpDefaultFilterInstances = {} 
    379      
    380     for filterName in __cpDefaultInputFilterNames: 
    381         filterClass = _cpDefaultFilterClasses[filterName] 
    382         filterInstance = _cpDefaultFilterInstances[filterName] = filterClass() 
    383         _cpDefaultInputFilterList.append(filterInstance) 
    384      
    385     for filterName in __cpDefaultOutputFilterNames: 
    386         filterClass = _cpDefaultFilterClasses[filterName] 
    387         filterInstance = _cpDefaultFilterInstances.setdefault(filterName, filterClass()) 
    388         _cpDefaultOutputFilterList.append(filterInstance) 
    389  
    390 def _cpInitUserDefinedFilters(): 
    391     filtersRoot = cherrypy.config.get('server.filtersRoot', []) 
    392     inputFiltersDict = cherrypy.config.get('server.inputFiltersDict', {}) 
    393     outputFiltersDict = cherrypy.config.get('server.outputFiltersDict', {}) 
    394      
    395     if len(filtersRoot) == 0: 
    396         return 
    397      
    398     sys.path.extend(filtersRoot) 
    399      
    400     for filterName, filterClassname in inputFiltersDict.items(): 
    401         filterModule = __import__(filterName, globals(),  locals(), []) 
    402         filterClass = getattr(filterModule, filterClassname, None) 
    403         filterInstance = filterClass() 
    404         _cpDefaultInputFilterList.append(filterInstance) 
    405      
    406     for filterName, filterClassname in outputFiltersDict.items(): 
    407         filterModule = __import__(filterName, globals(),  locals(), []) 
    408         filterClass = getattr(filterModule, filterClassname, None) 
    409         filterInstance = filterClass() 
    410         _cpDefaultOutputFilterList.append(filterInstance) 
    411      
    412     # Avoid pollution of the system path 
    413     for path in filtersRoot: 
    414         sys.path.remove(path) 
    415  
    416  
    417 # public domain "unrepr" implementation, found on the web and then improved. 
    418 import compiler 
    419  
    420 def getObj(s): 
    421     s = "a=" + s 
    422     p = compiler.parse(s) 
    423     return p.getChildren()[1].getChildren()[0].getChildren()[1] 
    424  
    425  
    426 class UnknownType(Exception): 
    427     pass 
    428  
    429  
    430 class Builder: 
    431      
    432     def build(self, o): 
    433         m = getattr(self, 'build_' + o.__class__.__name__, None) 
    434         if m is None: 
    435             raise UnknownType(o.__class__.__name__) 
    436         return m(o) 
    437      
    438     def build_List(self, o): 
    439         return map(self.build, o.getChildren()) 
    440      
    441     def build_Const(self, o): 
    442         return o.value 
    443      
    444     def build_Dict(self, o): 
    445         d = {} 
    446         i = iter(map(self.build, o.getChildren())) 
    447         for el in i: 
    448             d[el] = i.next() 
    449         return d 
    450      
    451     def build_Tuple(self, o): 
    452         return tuple(self.build_List(o)) 
    453      
    454     def build_Name(self, o): 
    455         if o.name == 'None': 
    456             return None 
    457         if o.name == 'True': 
    458             return True 
    459         if o.name == 'False': 
    460             return False 
    461          
    462         # See if the Name is a package or module 
    463         try: 
    464             return modules(o.name) 
    465         except ImportError: 
    466             pass 
    467          
    468         raise UnknownType(o.name) 
    469      
    470     def build_Add(self, o): 
    471         real, imag = map(self.build_Const, o.getChildren()) 
    472         try: 
    473             real = float(real) 
    474         except TypeError: 
    475             raise UnknownType('Add') 
    476         if not isinstance(imag, complex) or imag.real != 0.0: 
    477             raise UnknownType('Add') 
    478         return real+imag 
    479      
    480     def build_Getattr(self, o): 
    481         parent = self.build(o.expr) 
    482         return getattr(parent, o.attrname) 
    483  
    484  
    485 def unrepr(s): 
    486     if not s: 
    487         return s 
    488     try: 
    489         return Builder().build(getObj(s)) 
    490     except: 
    491         raise cherrypy.WrongUnreprValue(repr(s)) 
    492  
    493 def modules(modulePath): 
    494     """Load a module and retrieve a reference to that module.""" 
    495     try: 
    496         mod = sys.modules[modulePath] 
    497         if mod is None: 
    498             raise KeyError() 
    499     except KeyError: 
    500         # The last [''] is important. 
    501         mod = __import__(modulePath, globals(), locals(), ['']) 
    502     return mod 
    503  
    504 def attributes(fullAttributeName): 
    505     """Load a module and retrieve an attribute of that module.""" 
    506      
    507     # Parse out the path, module, and attribute 
    508     lastDot = fullAttributeName.rfind(u".") 
    509     attrName = fullAttributeName[lastDot + 1:] 
    510     modPath = fullAttributeName[:lastDot] 
    511      
    512     aMod = modules(modPath) 
    513     # Let an AttributeError propagate outward. 
    514     try: 
    515         attr = getattr(aMod, attrName) 
    516     except AttributeError: 
    517         raise AttributeError("'%s' object has no attribute '%s'" 
    518                              % (modPath, attrName)) 
    519      
    520     # Return a reference to the attribute. 
    521     return attr 
  • trunk/cherrypy/config.py

    r768 r807  
    44 
    55import cherrypy 
    6 from cherrypy import _cputil, _cperror 
    7 from cherrypy.lib import autoreload 
     6from cherrypy import _cputil 
     7from cherrypy.lib import autoreload, cptools 
    88 
    99 
     
    198198            value = configParser.get(section, option) 
    199199            try: 
    200                 value = _cputil.unrepr(value) 
    201             except _cperror.WrongUnreprValue, s: 
     200                value = cptools.unrepr(value) 
     201            except cherrypy.WrongUnreprValue, s: 
    202202                msg = ("section: %s, option: %s, value: %s" % 
    203203                       (repr(section), repr(option), repr(value))) 
    204                 raise _cperror.WrongConfigValue(msg) 
     204                raise cherrypy.WrongConfigValue(msg) 
    205205            result[section][option] = value 
    206206    return result 
  • trunk/cherrypy/lib/cptools.py

    r790 r807  
    181181        chunk = input.read(chunkSize) 
    182182    input.close() 
     183 
     184def modules(modulePath): 
     185    """Load a module and retrieve a reference to that module.""" 
     186    try: 
     187        mod = sys.modules[modulePath] 
     188        if mod is None: 
     189            raise KeyError() 
     190    except KeyError: 
     191        # The last [''] is important. 
     192        mod = __import__(modulePath, globals(), locals(), ['']) 
     193    return mod 
     194 
     195def attributes(fullAttributeName): 
     196    """Load a module and retrieve an attribute of that module.""" 
     197     
     198    # Parse out the path, module, and attribute 
     199    lastDot = fullAttributeName.rfind(u".") 
     200    attrName = fullAttributeName[lastDot + 1:] 
     201    modPath = fullAttributeName[:lastDot] 
     202     
     203    aMod = modules(modPath) 
     204    # Let an AttributeError propagate outward. 
     205    try: 
     206        attr = getattr(aMod, attrName) 
     207    except AttributeError: 
     208        raise AttributeError("'%s' object has no attribute '%s'" 
     209                             % (modPath, attrName)) 
     210     
     211    # Return a reference to the attribute. 
     212    return attr 
     213 
     214 
     215# public domain "unrepr" implementation, found on the web and then improved. 
     216import compiler 
     217 
     218def getObj(s): 
     219    s = "a=" + s 
     220    p = compiler.parse(s) 
     221    return p.getChildren()[1].getChildren()[0].getChildren()[1] 
     222 
     223 
     224class UnknownType(Exception): 
     225    pass 
     226 
     227 
     228class Builder: 
     229     
     230    def build(self, o): 
     231        m = getattr(self, 'build_' + o.__class__.__name__, None) 
     232        if m is None: 
     233            raise UnknownType(o.__class__.__name__) 
     234        return m(o) 
     235     
     236    def build_List(self, o): 
     237        return map(self.build, o.getChildren()) 
     238     
     239    def build_Const(self, o): 
     240        return o.value 
     241     
     242    def build_Dict(self, o): 
     243        d = {} 
     244        i = iter(map(self.build, o.getChildren())) 
     245        for el in i: 
     246            d[el] = i.next() 
     247        return d 
     248     
     249    def build_Tuple(self, o): 
     250        return tuple(self.build_List(o)) 
     251     
     252    def build_Name(self, o): 
     253        if o.name == 'None': 
     254            return None 
     255        if o.name == 'True': 
     256            return True 
     257        if o.name == 'False': 
     258            return False 
     259         
     260        # See if the Name is a package or module 
     261        try: 
     262            return modules(o.name) 
     263        except ImportError: 
     264            pass 
     265         
     266        raise UnknownType(o.name) 
     267     
     268    def build_Add(self, o): 
     269        real, imag = map(self.build_Const, o.getChildren()) 
     270        try: 
     271            real = float(real) 
     272        except TypeError: 
     273            raise UnknownType('Add') 
     274        if not isinstance(imag, complex) or imag.real != 0.0: 
     275            raise UnknownType('Add') 
     276        return real+imag 
     277     
     278    def build_Getattr(self, o): 
     279        parent = self.build(o.expr) 
     280        return getattr(parent, o.attrname) 
     281 
     282 
     283def unrepr(s): 
     284    if not s: 
     285        return s 
     286    try: 
     287        return Builder().build(getObj(s)) 
     288    except: 
     289        raise cherrypy.WrongUnreprValue(repr(s)) 
     290 
  • trunk/cherrypy/lib/filter/__init__.py

    r762 r807  
     1import cherrypy 
     2from cherrypy import _cputil 
     3 
     4# Filters that are always included 
     5from cherrypy.lib.filter import baseurlfilter, cachefilter, \ 
     6    decodingfilter, encodingfilter, gzipfilter, logdebuginfofilter, \ 
     7    staticfilter, nsgmlsfilter, tidyfilter, \ 
     8    xmlrpcfilter, sessionauthenticatefilter, \ 
     9    sessionfilter 
     10 
     11# this contains the classes for each filter type 
     12# we do not store the instances here because the test 
     13# suite must reinitialize the filters without restarting 
     14# the server 
     15_classes = { 
     16    'BaseUrlFilter'      : baseurlfilter.BaseUrlFilter, 
     17    'CacheFilter'        : cachefilter.CacheFilter, 
     18    'DecodingFilter'     : decodingfilter.DecodingFilter, 
     19    'EncodingFilter'     : encodingfilter.EncodingFilter, 
     20    'GzipFilter'         : gzipfilter.GzipFilter, 
     21    'LogDebugInfoFilter' : logdebuginfofilter.LogDebugInfoFilter, 
     22    'NsgmlsFilter'       : nsgmlsfilter.NsgmlsFilter, 
     23    'SessionAuthenticateFilter' : sessionauthenticatefilter.SessionAuthenticateFilter, 
     24    'SessionFilter'      : sessionfilter.SessionFilter, 
     25    'StaticFilter'       : staticfilter.StaticFilter, 
     26    'TidyFilter'         : tidyfilter.TidyFilter, 
     27    'XmlRpcFilter'       : xmlrpcfilter.XmlRpcFilter, 
     28} 
     29 
     30# These are in order for a reason! 
     31# They must be strings matching keys in _classes 
     32_input_order = [ 
     33    'CacheFilter', 
     34    'LogDebugInfoFilter', 
     35    'BaseUrlFilter', 
     36    'DecodingFilter', 
     37    'SessionFilter', 
     38    'SessionAuthenticateFilter', 
     39    'StaticFilter', 
     40    'NsgmlsFilter', 
     41    'TidyFilter', 
     42    'XmlRpcFilter', 
     43] 
     44 
     45_output_order = [ 
     46    'XmlRpcFilter', 
     47    'EncodingFilter', 
     48    'TidyFilter', 
     49    'NsgmlsFilter', 
     50    'LogDebugInfoFilter', 
     51    'GzipFilter', 
     52    'SessionFilter', 
     53    'CacheFilter', 
     54] 
     55 
     56_input_methods = ['onStartResource', 'beforeRequestBody', 'beforeMain'] 
     57_output_methods = ['beforeFinalize', 'onEndResource', 
     58                   'beforeErrorResponse', 'afterErrorResponse'] 
     59 
     60 
     61def init(): 
     62    """Initialize the filters.""" 
     63    instances = {} 
     64    inputs, outputs = [], [] 
     65     
     66    conf = cherrypy.config.get 
     67     
     68    for name in _input_order + conf('server.inputFilters', []): 
     69        f = instances.get(name) 
     70        if f is None: 
     71            f = instances[name] = _classes[name]() 
     72        inputs.append(f) 
     73     
     74    for name in conf('server.outputFilters', []) + _output_order: 
     75        f = instances.get(name) 
     76        if f is None: 
     77            f = instances[name] = _classes[name]() 
     78        outputs.append(f) 
     79     
     80    # Transform the instance lists into a dict of methods 
     81    _filterhooks.clear() 
     82    for name in _input_methods: 
     83        _filterhooks[name] = [] 
     84        for f in inputs: 
     85            method = getattr(f, name, None) 
     86            if method: 
     87                _filterhooks[name].append(method) 
     88    for name in _output_methods: 
     89        _filterhooks[name] = [] 
     90        for f in outputs: 
     91            method = getattr(f, name, None) 
     92            if method: 
     93                _filterhooks[name].append(method) 
     94 
     95 
     96_filterhooks = {} 
     97 
     98 
     99def applyFilters(methodName): 
     100    """Execute the given method for all registered filters.""" 
     101    special_methods = [] 
     102    for f in _cputil.getSpecialAttribute("_cpFilterList"): 
     103        method = getattr(f, methodName, None) 
     104        if method: 
     105            special_methods.append(method) 
     106     
     107    if methodName in _input_methods: 
     108        # Run special filters after defaults. 
     109        for method in _filterhooks[methodName] + special_methods: 
     110            method() 
     111    else: 
     112        # Run special filters before defaults. 
     113        for method in special_methods + _filterhooks[methodName]: 
     114            method() 
  • trunk/cherrypy/test/helper.py

    r799 r807  
    193193        cherrypy.config.reset() 
    194194        setConfig(conf) 
    195         cherrypy._cputil._cpInitDefaultFilters() 
     195        from cherrypy.lib import filter 
     196        filter.init() 
    196197         
    197198        suite = CPTestLoader.loadTestsFromName(testmod) 
     
    208209def _test_main_thread(): 
    209210    cherrypy.server.wait() 
    210     cherrypy._cputil._cpInitDefaultFilters() 
     211    from cherrypy.lib import filter 
     212    filter.init() 
    211213    try: 
    212214        webtest.main() 
  • trunk/cherrypy/test/test.py

    r778 r807  
    316316        'test_cache_filter', 
    317317        'test_combinedfilters', 
     318        'test_config', 
    318319        'test_core', 
    319320        'test_decodingencoding_filter', 

Hosted by WebFaction

Log in as guest/cpguest to create tickets