Changeset 1069
- Timestamp:
- 04/25/06 02:11:16
- Files:
-
- trunk/cherrypy/_cprequest.py (modified) (4 diffs)
- trunk/cherrypy/_cputil.py (modified) (1 diff)
- trunk/cherrypy/config.py (modified) (1 diff)
- trunk/cherrypy/lib/cptools.py (modified) (1 diff)
- trunk/cherrypy/lib/static.py (modified) (1 diff)
- trunk/cherrypy/test/test.py (modified) (2 diffs)
- trunk/cherrypy/test/test_config.py (modified) (1 diff)
- trunk/cherrypy/test/test_core.py (modified) (5 diffs)
- trunk/cherrypy/test/test_response_headers_filter.py (modified) (1 diff)
- trunk/cherrypy/tools.py (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
trunk/cherrypy/_cprequest.py
r1062 r1069 9 9 from cherrypy import _cputil, _cpcgifs, tools 10 10 from 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.configs30 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)] = v41 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.failsafe58 for callback in self.callbacks[point]:59 # Some hookpoints guarantee all callbacks are run even if60 # others at the same hookpoint fail. We will still log the61 # failure, but proceed on to the next callback. The only way62 # to stop all processing from one of these callbacks is63 # to raise SystemExit and stop the whole server. So, trap64 # your own errors in these callbacks!65 if failsafe:66 try:67 callback()68 except (KeyboardInterrupt, SystemExit):69 raise70 except:71 cherrypy.log(traceback=True)72 else:73 callback()74 75 11 76 12 … … 94 30 self.closed = False 95 31 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) 100 37 self.hooks.failsafe = ['on_start_resource', 'on_end_resource', 101 38 'on_end_request'] … … 151 88 # right away. 152 89 self.processRequestLine() 153 self.hooks. populate_from_config()90 self.hooks.setup() 154 91 155 92 try: … … 486 423 487 424 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')() 493 428 494 429 def setBareError(self, body=None): trunk/cherrypy/_cputil.py
r1049 r1069 228 228 return template % kwargs 229 229 230 def _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() 230 238 231 239 def _cp_on_http_error(status, message): trunk/cherrypy/config.py
r1057 r1069 150 150 else: 151 151 return result 152 153 def 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 152 171 153 172 trunk/cherrypy/lib/cptools.py
r1068 r1069 223 223 224 224 def 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): 227 227 228 228 if login_screen is None: trunk/cherrypy/lib/static.py
r1061 r1069 86 86 87 87 if not modified_since(path, stat): 88 response.body = [] 88 89 return [] 89 90 trunk/cherrypy/test/test.py
r1047 r1069 140 140 print """CherryPy Test Program 141 141 Usage: 142 test.py --server=* --1. 1--cover --basedir=path --profile --tests**142 test.py --server=* --1.0 --cover --basedir=path --profile --tests** 143 143 144 144 """ … … 152 152 print """ 153 153 154 --1. 1: use HTTP/1.1 servers instead of default HTTP/1.0154 --1.0: use HTTP/1.0 servers instead of default HTTP/1.1 155 155 156 156 --cover: turn on code-coverage tool trunk/cherrypy/test/test_config.py
r1047 r1069 95 95 err = ('WrongConfigValue: ("section: ' 96 96 "'global', option: 'server.environment', value: 'production'" 97 '''", 'UnknownType' , ('production',))''')97 '''", 'UnknownType')''') 98 98 self.getPage("/env/wrong") 99 99 self.assertErrorPage(500, pattern=err) trunk/cherrypy/test/test_core.py
r1057 r1069 5 5 6 6 import cherrypy 7 from cherrypy.lib import cptools, httptools, static 7 from cherrypy import tools 8 from cherrypy.lib import httptools, static 8 9 import types 9 10 … … 126 127 def stringify(self): 127 128 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 137 136 class InternalRedirect(Test): 138 139 _cp_filters = [LoginFilter()]140 137 141 138 def index(self): … … 154 151 raise cherrypy.InternalRedirect('/image/getImagesByUser') 155 152 153 @tools.login_redir.wrap() 156 154 def secure(self): 157 155 return "Welcome!" … … 335 333 return existing 336 334 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 337 340 cherrypy.config.update({ 338 341 'global': { 339 342 'server.log_to_screen': False, 343 'server.protocol_version': "HTTP/1.1", 340 344 'server.environment': 'production', 341 345 'server.show_tracebacks': True, … … 349 353 '/params': { 350 354 'server.log_file': log_file, 351 },352 '/internalredirect/secure': {353 'tools.auth.on': True,354 355 }, 355 356 '/error': { trunk/cherrypy/test/test_response_headers_filter.py
r1063 r1069 18 18 return "salut" 19 19 other.exposed = True 20 20 21 21 cherrypy.root = Root() 22 22 cherrypy.config.update({ trunk/cherrypy/tools.py
r1067 r1069 25 25 26 26 import cherrypy 27 from cherrypy import _cputil 28 29 30 class 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() 27 94 28 95

