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

Changeset 1143

Show
Ignore:
Timestamp:
06/12/06 15:25:03
Author:
fumanchu
Message:

Removed the wrap method from Tool, since the enable method should meet all cases better. Also fixed a bug where request.hooks was not being reinitialized on internalredirect. Also added code to guard against recursive internalredirects. Finally, fixed a couple of dict iterations that were missing iteritems.

Files:

Legend:

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

    r1141 r1143  
    6868         
    6969        self.closed = False 
    70          
    71         pts = ['on_start_resource', 'before_request_body', 
    72                'before_main', 'before_finalize', 
    73                'on_end_resource', 'on_end_request', 
    74                'before_error_response', 'after_error_response'] 
    75         self.hooks = HookMap(pts) 
    76         self.hooks.failsafe = ['on_start_resource', 'on_end_resource', 
    77                                'on_end_request'] 
    7870        self.redirections = [] 
    7971     
     
    151143                except cherrypy.InternalRedirect, ir: 
    152144                    pi = ir.path 
     145                    if (pi in self.redirections and 
     146                        not cherrypy.config.get("recursive_redirect")): 
     147                        raise RuntimeError("InternalRedirect visited the " 
     148                                           "same URL twice: %s" % repr(pi)) 
    153149                    self.redirections.append(pi) 
    154150        except (KeyboardInterrupt, SystemExit): 
     
    163159        try: 
    164160            try: 
     161                pts = ['on_start_resource', 'before_request_body', 
     162                       'before_main', 'before_finalize', 
     163                       'on_end_resource', 'on_end_request', 
     164                       'before_error_response', 'after_error_response'] 
     165                self.hooks = HookMap(pts) 
     166                self.hooks.failsafe = ['on_start_resource', 'on_end_resource', 
     167                                       'on_end_request'] 
     168                 
    165169                self.get_resource(path_info) 
    166170                self.tool_up() 
  • trunk/cherrypy/_cptools.py

    r1134 r1143  
    88        docstring. 
    99     
    10     Function decorators: if the tool exposes a "wrap" callable, that is 
    11         assumed to be a decorator for use in wrapping individual CherryPy 
    12         page handlers (methods on the CherryPy tree). The tool may choose 
    13         not to call the page handler at all, if the response has already 
    14         been populated
     10    Function decorators: 
     11        If the tool exposes an "enable" callable, that is assumed to be a 
     12        compile-time decorator for use in configuring individual CherryPy 
     13        page handlers (methods on the CherryPy tree). It should "turn on" 
     14        the tool in the decorated function's _cp_config attribute
    1515     
    1616    CherryPy hooks: "hooks" are points in the CherryPy request-handling 
     
    2929 
    3030class Tool(object): 
    31     """A registered function for use with CherryPy request-processing hooks.""" 
     31    """A registered function for use with CherryPy request-processing hooks. 
     32     
     33    help(tool.callable) should give you more information about this Tool. 
     34    """ 
    3235     
    3336    def __init__(self, point, callable, name=None): 
     
    4851        return conf 
    4952     
    50     def wrap(self, *args, **kwargs): 
    51         """Call-time decorator (wrap the handler with pre and post logic). 
    52          
    53         For example: 
    54          
    55             @tools.decode.wrap(encoding='chinese') 
    56             def mandarin(self, name): 
    57                 return "%s, ni hao shi jie" % name 
    58             mandarin.exposed = True 
    59         """ 
    60         def deco(f): 
    61             def wrapper(*a, **kw): 
    62                 self.callable(*args, **self.merged_args(kwargs)) 
    63                 return f(*a, **kw) 
    64             return wrapper 
    65         return deco 
    66      
    6753    def enable(self, **kwargs): 
    6854        """Compile-time decorator (turn on the tool in config). 
     
    7965                f._cp_config = {} 
    8066            f._cp_config["tools." + self.name + ".on"] = True 
    81             for k, v in kwargs
     67            for k, v in kwargs.iteritems()
    8268                f._cp_config["tools." + self.name + "." + k] = v 
    8369            return f 
     
    120106        return wrapper 
    121107     
    122     def wrap(self, *args, **kwargs): 
    123         """Make a decorator for this tool. 
    124          
    125         For example: 
    126          
    127             @tools.staticdir.wrap(section="/slides", dir="styles", root=absDir) 
    128             def slides(self, slide=None, style=None): 
    129                 return "No such file" 
    130             slides.exposed = True 
    131         """ 
    132         def deco(f): 
    133             def wrapper(*a, **kw): 
    134                 handled = self.callable(*args, **self.merged_args(kwargs)) 
    135                 if handled: 
    136                     return cherrypy.response.body 
    137                 else: 
    138                     return f(*a, **kw) 
    139             return wrapper 
    140         return deco 
    141      
    142108    def setup(self): 
    143109        """Hook this tool into cherrypy.request. 
     
    192158        self.point = "before_finalize" 
    193159        self.callable = _sessions.save 
    194         self.name = "sessions" 
    195      
    196     def wrap(self, **kwargs): 
    197         """Make a decorator for this tool.""" 
    198         def deco(f): 
    199             def wrapper(*a, **kw): 
    200                 conf = cherrypy.request.toolmap.get(self.name, {}).copy() 
    201                 conf.update(kwargs) 
    202                  
    203                 s = cherrypy.request._session = _sessions.Session() 
    204                 for k, v in conf.iteritems(): 
    205                     setattr(s, str(k), v) 
    206                 s.init() 
    207                 if not hasattr(cherrypy, "session"): 
    208                     cherrypy.session = _sessions.SessionWrapper() 
    209                  
    210                 result = f(*a, **kw) 
    211                 _sessions.save() 
    212                 cherrypy.request.hooks.attach('on_end_request', _sessions.cleanup) 
    213                 return result 
    214             return wrapper 
    215         return deco 
     160        self.name = None 
    216161     
    217162    def setup(self): 
  • trunk/cherrypy/lib/caching.py

    r1127 r1143  
    149149# CherryPy interfaces. Pick one. 
    150150 
    151 def wrap(f): 
    152     """Caching decorator.""" 
    153     def wrapper(*a, **kw): 
    154         # There's are no parameters to get(), so there's no need 
    155         # to merge values from config. 
    156         if not get(): 
    157             f(*a, **kw) 
    158             tee_output() 
     151def enable(**kwargs): 
     152    """Compile-time decorator (turn on the tool in config).""" 
     153    def wrapper(f): 
     154        if not hasattr(f, "_cp_config"): 
     155            f._cp_config = {} 
     156        f._cp_config["tools.caching.on"] = True 
     157        for k, v in kwargs: 
     158            f._cp_config["tools.caching." + k] = v 
     159        return f 
    159160    return wrapper 
    160161 
  • trunk/cherrypy/test/test_core.py

    r1141 r1143  
    162162         
    163163        # We support Python 2.3, but the @-deco syntax would look like this: 
    164         # @tools.login_redir.wrap() 
     164        # @tools.login_redir.enable() 
    165165        def secure(self): 
    166166            return "Welcome!" 
    167         secure = tools.login_redir.wrap()(secure) 
     167        secure = tools.login_redir.enable()(secure) 
     168        # Since enable returns the same function you pass in, 
     169        # you could skip binding the return value, and just write: 
     170        # tools.login_redir.enable()(secure) 
    168171         
    169172        def login(self): 
     
    325328            yield "<h1>Choose your document</h1>\n" 
    326329            yield "<ul>\n" 
    327             for id, contents in self.documents
     330            for id, contents in self.documents.iteritems()
    328331                yield ("    <li><a href='/divorce/get?ID=%s'>%s</a>: %s</li>\n" 
    329332                       % (id, id, contents)) 
  • trunk/cherrypy/test/test_response_headers.py

    r1134 r1143  
    44import cherrypy 
    55from cherrypy import tools 
    6 headers = tools.response_headers.wrap 
    76 
    87 
     
    1110        def index(self): 
    1211            yield "Hello, world" 
    13         index = headers([("Content-Language", "en-GB"), 
    14                          ('Content-Type', 'text/plain')])(index) 
    1512        index.exposed = True 
     13        h = [("Content-Language", "en-GB"), ('Content-Type', 'text/plain')] 
     14        tools.response_headers.enable(headers=h)(index) 
    1615         
    1716        def other(self): 
  • trunk/cherrypy/test/test_tools.py

    r1138 r1143  
    7474            yield europoundUnicode 
    7575        euro.exposed = True 
    76          
    77         # METHOD FOUR: decorator using Tool.enable 
    78         # We support Python 2.3, but the @-deco syntax would look like this: 
    79         # @tools.base_url.enable() 
    80         def base(self): 
    81             return cherrypy.request.base 
    82         base = tools.base_url.enable()(base) 
    83         base.exposed = True 
    8476     
    8577    root = Root() 
     
    119111            yield "confidential" 
    120112         
    121         # METHOD TWO: decorator using Tool.wrap 
     113        # METHOD TWO: decorator using Tool.enable 
    122114        # We support Python 2.3, but the @-deco syntax would look like this: 
    123         # @tools.check_access.wrap() 
     115        # @tools.check_access.enable() 
    124116        def restricted(self): 
    125117            return "Welcome!" 
    126         restricted = tools.check_access.wrap()(restricted) 
     118        restricted = tools.check_access.enable()(restricted) 
    127119         
    128120        def err_in_onstart(self): 
     
    194186        self.assertBody("True") 
    195187         
    196         # Test the "wrap" technique (call-time decorator). 
     188        # Test the "enable" technique (compile-time decorator). 
    197189        self.getPage("/demo/restricted") 
    198190        self.assertErrorPage(401) 
    199          
    200         # Test the "enable" technique (compile-time decorator). 
    201         self.getPage("/base", headers=[('X-Forwarded-Host', 
    202                                         'www.myforward.com')]) 
    203         self.assertBody("http://www.myforward.com") 
    204191     
    205192    def testGuaranteedHooks(self): 

Hosted by WebFaction

Log in as guest/cpguest to create tickets