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

Changeset 1069

Show
Ignore:
Timestamp:
04/25/06 02:11:16
Author:
fumanchu
Message:

test_core works again.

  1. I'll look at replacing _cp_on_error with Tools some other day.
  2. Moved the HookMap? into tools.py.
  3. New config.current_config function.
  4. static.serve_file now sets body even if not modified_since.
Files:

Legend:

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

    r1062 r1069  
    99from cherrypy import _cputil, _cpcgifs, tools 
    1010from cherrypy.lib import cptools, httptools 
    11  
    12  
    13 class HookMap(object): 
    14      
    15     def __init__(self, points=None, failsafe=None): 
    16         points = points or [] 
    17         self.callbacks = dict([(point, []) for point in points]) 
    18         self.failsafe = failsafe or [] 
    19      
    20     def attach(self, point, callback, conf=None): 
    21         if conf is None: 
    22             self.callbacks[point].append(callback) 
    23         else: 
    24             def wrapper(): 
    25                 callback(**conf) 
    26             self.callbacks[point].append(wrapper) 
    27      
    28     def populate_from_config(self): 
    29         configs = cherrypy.config.configs 
    30         collapsed_map = {} 
    31          
    32         def collect_tools(section): 
    33             local_conf = configs.get(section, {}) 
    34             for k, v in local_conf.iteritems(): 
    35                 atoms = k.split(".") 
    36                 namespace = atoms.pop(0) 
    37                 if namespace == "tools": 
    38                     toolname = atoms.pop(0) 
    39                     bucket = collapsed_map.setdefault(toolname, {}) 
    40                     bucket[".".join(atoms)] = v 
    41          
    42         collect_tools("global") 
    43         path = "" 
    44         for b in cherrypy.request.object_path.split('/'): 
    45             if path == "/": 
    46                 path = "" 
    47             path = "/".join((path, b)) 
    48             collect_tools(path) 
    49          
    50         for toolname, conf in collapsed_map.iteritems(): 
    51             if conf.get("on", False): 
    52                 del conf["on"] 
    53                 getattr(tools, toolname).setup(conf) 
    54      
    55     def run(self, point): 
    56         """Execute all registered callbacks for the given point.""" 
    57         failsafe = point in self.failsafe 
    58         for callback in self.callbacks[point]: 
    59             # Some hookpoints guarantee all callbacks are run even if 
    60             # others at the same hookpoint fail. We will still log the 
    61             # failure, but proceed on to the next callback. The only way 
    62             # to stop all processing from one of these callbacks is 
    63             # to raise SystemExit and stop the whole server. So, trap 
    64             # your own errors in these callbacks! 
    65             if failsafe: 
    66                 try: 
    67                     callback() 
    68                 except (KeyboardInterrupt, SystemExit): 
    69                     raise 
    70                 except: 
    71                     cherrypy.log(traceback=True) 
    72             else: 
    73                 callback() 
    74  
    7511 
    7612 
     
    9430        self.closed = False 
    9531         
    96         self.hooks = HookMap(['on_start_resource', 'before_request_body', 
    97                               'before_main', 'before_finalize', 
    98                               'on_end_resource', 'on_end_request', 
    99                               'before_error_response', 'after_error_response']) 
     32        pts = ['on_start_resource', 'before_request_body', 
     33               'before_main', 'before_finalize', 
     34               'on_end_resource', 'on_end_request', 
     35               'before_error_response', 'after_error_response'] 
     36        self.hooks = tools.HookMap(pts) 
    10037        self.hooks.failsafe = ['on_start_resource', 'on_end_resource', 
    10138                               'on_end_request'] 
     
    15188            # right away. 
    15289            self.processRequestLine() 
    153             self.hooks.populate_from_config() 
     90            self.hooks.setup() 
    15491             
    15592            try: 
     
    486423     
    487424    def error_response(self): 
    488         # Allow logging of only *unexpected* HTTPError's. 
    489         if (not cherrypy.config.get('server.log_tracebacks', True) 
    490             and cherrypy.config.get('server.log_unhandled_tracebacks', True)): 
    491             cherrypy.log(traceback=True) 
    492         cherrypy.HTTPError(500).set_response() 
     425        # _cp_on_error will probably change self.body. 
     426        # It may also change the headers, etc. 
     427        _cputil.get_special_attribute('_cp_on_error', '_cpOnError')() 
    493428     
    494429    def setBareError(self, body=None): 
  • trunk/cherrypy/_cputil.py

    r1049 r1069  
    228228    return template % kwargs 
    229229 
     230def _cp_on_error(): 
     231    """ Default _cp_on_error method """ 
     232    # Allow logging of only *unexpected* HTTPError's. 
     233    if (not cherrypy.config.get('server.log_tracebacks', True) 
     234        and cherrypy.config.get('server.log_unhandled_tracebacks', True)): 
     235        cherrypy.log(traceback=True) 
     236     
     237    cherrypy.HTTPError(500).set_response() 
    230238 
    231239def _cp_on_http_error(status, message): 
  • trunk/cherrypy/config.py

    r1057 r1069  
    150150    else: 
    151151        return result 
     152 
     153def current_config(path=None): 
     154    """Return all configs in effect for the given path in a single dict.""" 
     155    if path is None: 
     156        try: 
     157            path = cherrypy.request.object_path 
     158        except AttributeError: 
     159            # There's no request.object_path yet, so use the global settings. 
     160            path = "global" 
     161     
     162    result = {} 
     163    result.update(configs.get("global", {})) 
     164    curpath = "" 
     165    for b in path.split('/'): 
     166        if curpath == "/": 
     167            curpath = "" 
     168        curpath = "/".join((curpath, b)) 
     169        result.update(configs.get(curpath, {})) 
     170    return result 
    152171 
    153172 
  • trunk/cherrypy/lib/cptools.py

    r1068 r1069  
    223223 
    224224def session_auth(check_login_and_password=None, not_logged_in=None, 
    225                  load_user_by_username=None, session_key = 'username', 
    226                  on_login = None, on_logout = None, login_screen = None): 
     225                 load_user_by_username=None, session_key='username', 
     226                 on_login=None, on_logout=None, login_screen=None): 
    227227     
    228228    if login_screen is None: 
  • trunk/cherrypy/lib/static.py

    r1061 r1069  
    8686     
    8787    if not modified_since(path, stat): 
     88        response.body = [] 
    8889        return [] 
    8990     
  • trunk/cherrypy/test/test.py

    r1047 r1069  
    140140        print """CherryPy Test Program 
    141141    Usage: 
    142         test.py --server=* --1.1 --cover --basedir=path --profile --tests** 
     142        test.py --server=* --1.0 --cover --basedir=path --profile --tests** 
    143143         
    144144    """ 
     
    152152        print """ 
    153153     
    154     --1.1: use HTTP/1.1 servers instead of default HTTP/1.0 
     154    --1.0: use HTTP/1.0 servers instead of default HTTP/1.1 
    155155     
    156156    --cover: turn on code-coverage tool 
  • trunk/cherrypy/test/test_config.py

    r1047 r1069  
    9595        err = ('WrongConfigValue: ("section: ' 
    9696               "'global', option: 'server.environment', value: 'production'" 
    97                '''", 'UnknownType', ('production',))''') 
     97               '''", 'UnknownType')''') 
    9898        self.getPage("/env/wrong") 
    9999        self.assertErrorPage(500, pattern=err) 
  • trunk/cherrypy/test/test_core.py

    r1057 r1069  
    55 
    66import cherrypy 
    7 from cherrypy.lib import cptools, httptools, static 
     7from cherrypy import tools 
     8from cherrypy.lib import httptools, static 
    89import types 
    910 
     
    126127        def stringify(self): 
    127128            return str(cherrypy.HTTPRedirect("/")) 
    128  
    129  
    130     class LoginFilter: 
    131          
    132         def before_main(self): 
    133             if cherrypy.config.get("auth.on", False): 
    134                 if not getattr(cherrypy.request, "login", None): 
    135                     raise cherrypy.InternalRedirect("/internalredirect/login") 
    136  
     129     
     130     
     131    def login_redir(): 
     132        if not getattr(cherrypy.request, "login", None): 
     133            raise cherrypy.InternalRedirect("/internalredirect/login") 
     134    tools.login_redir = tools.Tool('before_main', login_redir) 
     135     
    137136    class InternalRedirect(Test): 
    138          
    139         _cp_filters = [LoginFilter()] 
    140137         
    141138        def index(self): 
     
    154151                raise cherrypy.InternalRedirect('/image/getImagesByUser') 
    155152         
     153        @tools.login_redir.wrap() 
    156154        def secure(self): 
    157155            return "Welcome!" 
     
    335333            return existing 
    336334     
     335    def check(login, password): 
     336        # Dummy check_login_and_password function 
     337        if login != 'login' or password != 'password': 
     338            return u'Wrong login/password' 
     339     
    337340    cherrypy.config.update({ 
    338341        'global': { 
    339342            'server.log_to_screen': False, 
     343            'server.protocol_version': "HTTP/1.1", 
    340344            'server.environment': 'production', 
    341345            'server.show_tracebacks': True, 
     
    349353        '/params': { 
    350354            'server.log_file': log_file, 
    351         }, 
    352         '/internalredirect/secure': { 
    353             'tools.auth.on': True, 
    354355        }, 
    355356        '/error': { 
  • trunk/cherrypy/test/test_response_headers_filter.py

    r1063 r1069  
    1818            return "salut" 
    1919        other.exposed = True 
    20  
     20     
    2121    cherrypy.root = Root() 
    2222    cherrypy.config.update({ 
  • trunk/cherrypy/tools.py

    r1067 r1069  
    2525 
    2626import cherrypy 
     27from cherrypy import _cputil 
     28 
     29 
     30class HookMap(object): 
     31     
     32    def __init__(self, points=None, failsafe=None): 
     33        points = points or [] 
     34        self.callbacks = dict([(point, []) for point in points]) 
     35        self.failsafe = failsafe or [] 
     36     
     37    def attach(self, point, callback, conf=None): 
     38        if conf is None: 
     39            self.callbacks[point].append(callback) 
     40        else: 
     41            def wrapper(): 
     42                callback(**conf) 
     43            self.callbacks[point].append(wrapper) 
     44     
     45    def tool_config(self): 
     46        toolmap = {} 
     47        for k, v in cherrypy.config.current_config().iteritems(): 
     48            atoms = k.split(".") 
     49            namespace = atoms.pop(0) 
     50            if namespace == "tools": 
     51                toolname = atoms.pop(0) 
     52                bucket = toolmap.setdefault(toolname, {}) 
     53                bucket[".".join(atoms)] = v 
     54        return toolmap 
     55     
     56    def setup(self): 
     57        """Run tool.setup(conf) for each tool specified in current config.""" 
     58        g = globals() 
     59        for toolname, conf in self.tool_config().iteritems(): 
     60            if conf.get("on", False): 
     61                del conf["on"] 
     62                g[toolname].setup(conf) 
     63         
     64        # Run _cp_setup_hooks functions 
     65        mounted_app_roots = cherrypy.tree.mount_points.values() 
     66        objectList = _cputil.get_object_trail() 
     67        objectList.reverse() 
     68        for objname, obj in objectList: 
     69            s = getattr(obj, "_cp_setup_hooks", None) 
     70            if s: 
     71                s() 
     72            if obj in mounted_app_roots: 
     73                break 
     74     
     75    def run(self, point): 
     76        """Execute all registered callbacks for the given point.""" 
     77        failsafe = point in self.failsafe 
     78        for callback in self.callbacks[point]: 
     79            # Some hookpoints guarantee all callbacks are run even if 
     80            # others at the same hookpoint fail. We will still log the 
     81            # failure, but proceed on to the next callback. The only way 
     82            # to stop all processing from one of these callbacks is 
     83            # to raise SystemExit and stop the whole server. So, trap 
     84            # your own errors in these callbacks! 
     85            if failsafe: 
     86                try: 
     87                    callback() 
     88                except (KeyboardInterrupt, SystemExit): 
     89                    raise 
     90                except: 
     91                    cherrypy.log(traceback=True) 
     92            else: 
     93                callback() 
    2794 
    2895 

Hosted by WebFaction

Log in as guest/cpguest to create tickets