Changeset 2461
- Timestamp:
- 06/24/09 00:10:34
- Files:
-
- branches/python3/cherrypy/_cpdispatch.py (modified) (10 diffs)
- branches/python3/cherrypy/_cperror.py (modified) (12 diffs)
- branches/python3/cherrypy/_cplogging.py (modified) (6 diffs)
- branches/python3/cherrypy/_cpmodpy.py (modified) (1 diff)
- branches/python3/cherrypy/_cpreqbody.py (modified) (1 diff)
- branches/python3/cherrypy/_cprequest.py (modified) (11 diffs)
- branches/python3/cherrypy/_cptools.py (modified) (13 diffs)
- branches/python3/cherrypy/_cptree.py (modified) (2 diffs)
- branches/python3/cherrypy/lib/auth.py (modified) (5 diffs)
- branches/python3/cherrypy/lib/auth_basic.py (modified) (2 diffs)
- branches/python3/cherrypy/lib/auth_digest.py (modified) (4 diffs)
- branches/python3/cherrypy/lib/caching.py (modified) (7 diffs)
- branches/python3/cherrypy/lib/cptools.py (modified) (20 diffs)
- branches/python3/cherrypy/lib/encoding.py (modified) (9 diffs)
- branches/python3/cherrypy/lib/jsontools.py (modified) (2 diffs)
- branches/python3/cherrypy/lib/sessions.py (modified) (5 diffs)
- branches/python3/cherrypy/lib/static.py (modified) (8 diffs)
- branches/python3/cherrypy/process/wspbus.py (modified) (1 diff)
- branches/python3/cherrypy/test/benchmark.py (modified) (3 diffs)
- branches/python3/cherrypy/test/test.py (modified) (1 diff)
- branches/python3/cherrypy/test/test_dynamicobjectmapping.py (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
branches/python3/cherrypy/_cpdispatch.py
r2373 r2461 53 53 parameters are part of the request; if they are invalid a 400 Bad Request. 54 54 """ 55 show_mismatched_params = getattr(cherrypy.request, 'show_mismatched_params', False) 55 show_mismatched_params = getattr( 56 cherrypy.serving.request, 'show_mismatched_params', False) 56 57 try: 57 58 (args, varargs, varkw, defaults) = inspect.getargspec(callable) … … 120 121 raise cherrypy.HTTPError(404) 121 122 122 body_params = cherrypy. request.body.params or {}123 body_params = cherrypy.serving.request.body.params or {} 123 124 body_params = set(body_params.keys()) 124 125 qs_params = set(callable_kwargs.keys()) - body_params … … 177 178 178 179 def _get_kwargs(self): 179 kwargs = cherrypy. request.params.copy()180 kwargs = cherrypy.serving.request.params.copy() 180 181 if self._kwargs: 181 182 kwargs.update(self._kwargs) … … 245 246 positional arguments. 246 247 """ 247 request = cherrypy. request248 request = cherrypy.serving.request 248 249 app = request.app 249 250 root = app.root … … 356 357 def __call__(self, path_info): 357 358 """Set handler and config for the current request.""" 358 request = cherrypy. request359 request = cherrypy.serving.request 359 360 resource, vpath = self.find_handler(path_info) 360 361 … … 365 366 avail.append("HEAD") 366 367 avail.sort() 367 cherrypy. response.headers['Allow'] = ", ".join(avail)368 cherrypy.serving.response.headers['Allow'] = ", ".join(avail) 368 369 369 370 # Find the subhandler … … 414 415 func = self.find_handler(path_info) 415 416 if func: 416 cherrypy. request.handler = LateParamPageHandler(func)417 cherrypy.serving.request.handler = LateParamPageHandler(func) 417 418 else: 418 cherrypy. request.handler = cherrypy.NotFound()419 cherrypy.serving.request.handler = cherrypy.NotFound() 419 420 420 421 def find_handler(self, path_info): … … 422 423 import routes 423 424 424 request = cherrypy. request425 request = cherrypy.serving.request 425 426 426 427 config = routes.request_config() 427 428 config.mapper = self.mapper 428 if hasattr( cherrypy.request, 'wsgi_environ'):429 config.environ = cherrypy.request.wsgi_environ429 if hasattr(request, 'wsgi_environ'): 430 config.environ = request.wsgi_environ 430 431 config.host = request.headers.get('Host', None) 431 432 config.protocol = request.scheme … … 541 542 from cherrypy.lib import httputil 542 543 def vhost_dispatch(path_info): 543 header = cherrypy.request.headers.get 544 request = cherrypy.serving.request 545 header = request.headers.get 544 546 545 547 domain = header('Host', '') … … 554 556 555 557 # Touch up staticdir config. See http://www.cherrypy.org/ticket/614. 556 section = cherrypy.request.config.get('tools.staticdir.section')558 section = request.config.get('tools.staticdir.section') 557 559 if section: 558 560 section = section[len(prefix):] 559 cherrypy.request.config['tools.staticdir.section'] = section561 request.config['tools.staticdir.section'] = section 560 562 561 563 return result branches/python3/cherrypy/_cperror.py
r2450 r2461 5 5 from traceback import format_exception as _format_exception 6 6 from urllib.parse import urljoin as _urljoin 7 from cherrypy.lib import httputil 7 from cherrypy.lib import httputil as _httputil 8 8 9 9 … … 30 30 def __init__(self, path, query_string=""): 31 31 import cherrypy 32 request = cherrypy. request32 request = cherrypy.serving.request 33 33 34 34 self.query_string = query_string … … 61 61 def __init__(self, urls, status=None): 62 62 import cherrypy 63 request = cherrypy. request63 request = cherrypy.serving.request 64 64 65 65 if isinstance(urls, str): … … 100 100 """ 101 101 import cherrypy 102 response = cherrypy. response102 response = cherrypy.serving.response 103 103 response.status = status = self.status 104 104 … … 160 160 import cherrypy 161 161 162 response = cherrypy. response162 response = cherrypy.serving.response 163 163 164 164 # Remove headers which applied to the original content, … … 193 193 self.status = status 194 194 try: 195 self.code, self.reason, defaultmsg = httputil.valid_status(status)195 self.code, self.reason, defaultmsg = _httputil.valid_status(status) 196 196 except ValueError as x: 197 197 raise self.__class__(500, x.args[0]) … … 213 213 import cherrypy 214 214 215 response = cherrypy. response215 response = cherrypy.serving.response 216 216 217 217 clean_headers(self.code) … … 221 221 response.status = self.status 222 222 tb = None 223 if cherrypy. request.show_tracebacks:223 if cherrypy.serving.request.show_tracebacks: 224 224 tb = format_exc() 225 225 response.headers['Content-Type'] = "text/html;charset=utf-8" … … 246 246 if path is None: 247 247 import cherrypy 248 path = cherrypy.request.script_name + cherrypy.request.path_info 248 request = cherrypy.serving.request 249 path = request.script_name + request.path_info 249 250 self.args = (path,) 250 251 HTTPError.__init__(self, 404, "The path %r was not found." % path) … … 289 290 290 291 try: 291 code, reason, message = httputil.valid_status(status)292 code, reason, message = _httputil.valid_status(status) 292 293 except ValueError as x: 293 294 raise cherrypy.HTTPError(500, x.args[0]) … … 311 312 312 313 # Use a custom template or callable for the error page? 313 pages = cherrypy. request.error_page314 pages = cherrypy.serving.request.error_page 314 315 error_page = pages.get(code) or pages.get('default') 315 316 if error_page: … … 339 340 def _be_ie_unfriendly(status): 340 341 import cherrypy 341 response = cherrypy. response342 response = cherrypy.serving.response 342 343 343 344 # For some statuses, Internet Explorer 5+ shows "friendly error branches/python3/cherrypy/_cplogging.py
r2435 r2461 7 7 logfmt = logging.Formatter("%(message)s") 8 8 import os 9 import email.utils10 9 import sys 11 10 … … 73 72 which are written in their C-style notation (\\n, \\t, etc). 74 73 """ 75 request = cherrypy. request74 request = cherrypy.serving.request 76 75 remote = request.remote 77 response = cherrypy. response76 response = cherrypy.serving.response 78 77 outheaders = response.headers 79 78 inheaders = request.headers … … 89 88 'r': request.request_line, 90 89 's': status, 91 'b': outheaders.get('Content-Length', '') or "-",92 'f': inheaders.get('Referer', ''),93 'a': inheaders.get('User-Agent', ''),90 'b': dict.get(outheaders, 'Content-Length', '') or "-", 91 'f': dict.get(inheaders, 'Referer', ''), 92 'a': dict.get(inheaders, 'User-Agent', ''), 94 93 } 95 94 for k, v in atoms.items(): … … 117 116 """Return now() in Apache Common Log Format (no timezone).""" 118 117 now = datetime.datetime.now() 119 monthnames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 120 'aug', 'sep', 'oct', 'nov', 'dec', 121 'january', 'february', 'march', 'april', 'may', 'june', 'july', 122 'august', 'september', 'october', 'november', 'december'] 118 monthnames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 119 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] 123 120 month = monthnames[now.month - 1].capitalize() 124 121 return ('[%02d/%s/%04d:%02d:%02d:%02d]' % … … 230 227 """Flushes the stream.""" 231 228 try: 232 stream = cherrypy. request.wsgi_environ.get('wsgi.errors')229 stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors') 233 230 except (AttributeError, KeyError): 234 231 pass … … 239 236 """Emit a record.""" 240 237 try: 241 stream = cherrypy. request.wsgi_environ.get('wsgi.errors')238 stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors') 242 239 except (AttributeError, KeyError): 243 240 pass branches/python3/cherrypy/_cpmodpy.py
r2438 r2461 264 264 import os 265 265 import re 266 import subprocess 266 267 267 268 268 269 def read_process(cmd, args=""): 269 pipein, pipeout = os.popen4("%s %s" % (cmd, args)) 270 fullcmd = "%s %s" % (cmd, args) 271 p = subprocess.Popen(fullcmd, shell=True, 272 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, 273 close_fds=True) 270 274 try: 271 firstline = p ipeout.readline()272 if (re.search( r"(not recognized|No such file|not found)", firstline,275 firstline = p.stdout.readline() 276 if (re.search(b"(not recognized|No such file|not found)", firstline, 273 277 re.IGNORECASE)): 274 278 raise IOError('%s must be on your system path.' % cmd) 275 output = firstline + p ipeout.read()279 output = firstline + p.stdout.read() 276 280 finally: 277 p ipeout.close()281 p.stdout.close() 278 282 return output 279 283 branches/python3/cherrypy/_cpreqbody.py
r2415 r2461 593 593 # however, app developers are responsible in that case to set 594 594 # cherrypy.request.process_body to False so this method isn't called. 595 h = cherrypy. request.headers595 h = cherrypy.serving.request.headers 596 596 if 'Content-Length' not in h and 'Transfer-Encoding' not in h: 597 597 raise cherrypy.HTTPError(411) branches/python3/cherrypy/_cprequest.py
r2451 r2461 133 133 if not isinstance(v, Hook): 134 134 v = Hook(v) 135 cherrypy. request.hooks[hookpoint].append(v)135 cherrypy.serving.request.hooks[hookpoint].append(v) 136 136 137 137 def request_namespace(k, v): 138 138 """Attach request attributes declared in config.""" 139 setattr(cherrypy. request, k, v)139 setattr(cherrypy.serving.request, k, v) 140 140 141 141 def response_namespace(k, v): … … 144 144 # http://cherrypy.org/ticket/889 145 145 if k[:8] == 'headers.': 146 cherrypy. response.headers[k.split('.', 1)[1]] = v146 cherrypy.serving.response.headers[k.split('.', 1)[1]] = v 147 147 else: 148 setattr(cherrypy. response, k, v)148 setattr(cherrypy.serving.response, k, v) 149 149 150 150 def error_page_namespace(k, v): … … 152 152 if k != 'default': 153 153 k = int(k) 154 cherrypy. request.error_page[k] = v154 cherrypy.serving.request.error_page[k] = v 155 155 156 156 … … 521 521 522 522 """ 523 response = cherrypy.serving.response 523 524 self.stage = 'run' 524 525 try: … … 545 546 sp = int(self.server_protocol[5]), int(self.server_protocol[7]) 546 547 self.protocol = min(rp, sp) 547 cherrypy.response.headers.protocol = self.protocol548 response.headers.protocol = self.protocol 548 549 549 550 # Rebuild first line of the request (e.g. "GET /path HTTP/1.0"). … … 584 585 body = "" 585 586 r = bare_error(body) 586 response = cherrypy.response587 587 response.output_status, response.header_list, response.body = r 588 588 589 589 if self.method == "HEAD": 590 590 # HEAD requests MUST NOT return a message-body in the response. 591 cherrypy.response.body = []591 response.body = [] 592 592 593 593 try: … … 596 596 cherrypy.log.error(traceback=True) 597 597 598 if cherrypy.response.timed_out:598 if response.timed_out: 599 599 raise cherrypy.TimeoutError() 600 600 601 return cherrypy.response601 return response 602 602 603 603 # Uncomment for stage debugging … … 606 606 def respond(self, path_info): 607 607 """Generate a response for the resource at self.path_info. (Core)""" 608 response = cherrypy.serving.response 608 609 try: 609 610 try: … … 646 647 if self.handler: 647 648 self.stage = 'handler' 648 cherrypy.response.body = self.handler()649 response.body = self.handler() 649 650 650 651 # Finalize 651 652 self.stage = 'before_finalize' 652 653 self.hooks.run('before_finalize') 653 cherrypy.response.finalize()654 response.finalize() 654 655 except (cherrypy.HTTPRedirect, cherrypy.HTTPError) as inst: 655 656 inst.set_response() 656 657 self.stage = 'before_finalize (HTTPError)' 657 658 self.hooks.run('before_finalize') 658 cherrypy.response.finalize()659 response.finalize() 659 660 finally: 660 661 self.stage = 'on_end_resource' … … 719 720 720 721 def get_resource(self, path): 721 722 722 """Call a dispatcher (which sets self.handler and .config). (Core)""" 723 723 dispatch = self.dispatch … … 752 752 self.error_response() 753 753 self.hooks.run("after_error_response") 754 cherrypy. response.finalize()754 cherrypy.serving.response.finalize() 755 755 except cherrypy.HTTPRedirect as inst: 756 756 inst.set_response() 757 cherrypy. response.finalize()757 cherrypy.serving.response.finalize() 758 758 759 759 # ------------------------- Properties ------------------------- # branches/python3/cherrypy/_cptools.py
r2396 r2461 87 87 conf = {} 88 88 89 tm = cherrypy. request.toolmaps[self.namespace]89 tm = cherrypy.serving.request.toolmaps[self.namespace] 90 90 if self._name in tm: 91 91 conf.update(tm[self._name]) … … 130 130 if p is None: 131 131 p = getattr(self.callable, "priority", self._priority) 132 cherrypy. request.hooks.attach(self._point, self.callable,133 priority=p, **conf)132 cherrypy.serving.request.hooks.attach(self._point, self.callable, 133 priority=p, **conf) 134 134 135 135 … … 160 160 if not handled: 161 161 raise cherrypy.NotFound() 162 return cherrypy. response.body162 return cherrypy.serving.response.body 163 163 handle_func.exposed = True 164 164 return handle_func … … 166 166 def _wrapper(self, **kwargs): 167 167 if self.callable(**kwargs): 168 cherrypy. request.handler = None168 cherrypy.serving.request.handler = None 169 169 170 170 def _setup(self): … … 178 178 if p is None: 179 179 p = getattr(self.callable, "priority", self._priority) 180 cherrypy. request.hooks.attach(self._point, self._wrapper,181 priority=p, **conf)180 cherrypy.serving.request.hooks.attach(self._point, self._wrapper, 181 priority=p, **conf) 182 182 183 183 … … 207 207 208 208 def callable(self): 209 innerfunc = cherrypy. request.handler209 innerfunc = cherrypy.serving.request.handler 210 210 def wrap(*args, **kwargs): 211 211 return self.newhandler(innerfunc, *args, **kwargs) 212 cherrypy. request.handler = wrap212 cherrypy.serving.request.handler = wrap 213 213 214 214 … … 228 228 method when the tool is "turned on" in config. 229 229 """ 230 cherrypy. request.error_response = self._wrapper230 cherrypy.serving.request.error_response = self._wrapper 231 231 232 232 … … 267 267 method when the tool is "turned on" in config. 268 268 """ 269 hooks = cherrypy. request.hooks269 hooks = cherrypy.serving.request.hooks 270 270 271 271 conf = self._merged_args() … … 359 359 raise Exception('method "%s" is not supported' % attr) 360 360 361 conf = cherrypy. request.toolmaps['tools'].get("xmlrpc", {})361 conf = cherrypy.serving.request.toolmaps['tools'].get("xmlrpc", {}) 362 362 _xmlrpc.respond(body, 363 363 conf.get('encoding', 'utf-8'), 364 364 conf.get('allow_none', 0)) 365 return cherrypy. response.body365 return cherrypy.serving.response.body 366 366 default.exposed = True 367 367 … … 379 379 380 380 def _wrapper(self, invalid_methods=("POST", "PUT", "DELETE"), **kwargs): 381 request = cherrypy. request381 request = cherrypy.serving.request 382 382 383 383 if not hasattr(cherrypy, "_cache"): … … 403 403 404 404 p = conf.pop("priority", None) 405 cherrypy. request.hooks.attach('before_handler', self._wrapper,406 priority=p, **conf)405 cherrypy.serving.request.hooks.attach('before_handler', self._wrapper, 406 priority=p, **conf) 407 407 408 408 … … 428 428 def __enter__(self): 429 429 """Populate request.toolmaps from tools specified in config.""" 430 cherrypy. request.toolmaps[self.namespace] = map = {}430 cherrypy.serving.request.toolmaps[self.namespace] = map = {} 431 431 def populate(k, v): 432 432 toolname, arg = k.split(".", 1) … … 437 437 def __exit__(self, exc_type, exc_val, exc_tb): 438 438 """Run tool._setup() for each tool in our toolmap.""" 439 map = cherrypy. request.toolmaps.get(self.namespace)439 map = cherrypy.serving.request.toolmaps.get(self.namespace) 440 440 if map: 441 441 for name, settings in map.items(): branches/python3/cherrypy/_cptree.py
r2335 r2461 81 81 if self._script_name is None: 82 82 # None signals that the script name should be pulled from WSGI environ. 83 return cherrypy. request.wsgi_environ['SCRIPT_NAME'].rstrip("/")83 return cherrypy.serving.request.wsgi_environ['SCRIPT_NAME'].rstrip("/") 84 84 return self._script_name 85 85 def _set_script_name(self, value): … … 210 210 if path is None: 211 211 try: 212 path = httputil.urljoin(cherrypy.request.script_name, 213 cherrypy.request.path_info) 212 request = cherrypy.serving.request 213 path = httputil.urljoin(request.script_name, 214 request.path_info) 214 215 except AttributeError: 215 216 return None branches/python3/cherrypy/lib/auth.py
r2156 r2461 5 5 def check_auth(users, encrypt=None, realm=None): 6 6 """If an authorization header contains credentials, return True, else False.""" 7 if 'authorization' in cherrypy.request.headers: 7 request = cherrypy.serving.request 8 if 'authorization' in request.headers: 8 9 # make sure the provided credentials are correctly set 9 ah = httpauth.parseAuthorization( cherrypy.request.headers['authorization'])10 ah = httpauth.parseAuthorization(request.headers['authorization']) 10 11 if ah is None: 11 12 raise cherrypy.HTTPError(400, 'Bad Request') … … 18 19 # backward compatibility 19 20 users = users() # expect it to return a dictionary 20 21 21 22 if not isinstance(users, dict): 22 23 raise ValueError("Authentication users must be a dictionary") … … 36 37 # validate the authorization by re-computing it here 37 38 # and compare it with what the user-agent provided 38 if httpauth.checkResponse(ah, password, method= cherrypy.request.method,39 if httpauth.checkResponse(ah, password, method=request.method, 39 40 encrypt=encrypt, realm=realm): 40 cherrypy.request.login = ah["username"]41 request.login = ah["username"] 41 42 return True 42 43 cherrypy.request.login = False43 44 request.login = False 44 45 return False 45 46 … … 56 57 57 58 # inform the user-agent this path is protected 58 cherrypy. response.headers['www-authenticate'] = httpauth.basicAuth(realm)59 cherrypy.serving.response.headers['www-authenticate'] = httpauth.basicAuth(realm) 59 60 60 61 raise cherrypy.HTTPError(401, "You are not authorized to access that resource") … … 70 71 71 72 # inform the user-agent this path is protected 72 cherrypy. response.headers['www-authenticate'] = httpauth.digestAuth(realm)73 cherrypy.serving.response.headers['www-authenticate'] = httpauth.digestAuth(realm) 73 74 74 75 raise cherrypy.HTTPError(401, "You are not authorized to access that resource") branches/python3/cherrypy/lib/auth_basic.py
r2353 r2461 60 60 returns True, else it returns False. 61 61 """ 62 62 63 63 if '"' in realm: 64 64 raise ValueError('Realm cannot contain the " (quote) character.') 65 66 auth_header = cherrypy.request.headers.get('authorization') 65 request = cherrypy.serving.request 66 67 auth_header = request.headers.get('authorization') 67 68 if auth_header is not None: 68 69 try: … … 74 75 username, password = username_password.decode("ISO-8859-1").split(':', 1) 75 76 if checkpassword(realm, username, password): 76 cherrypy.request.login = username77 request.login = username 77 78 return # successful authentication 78 79 except (ValueError, binascii.Error): # split() error, base64.decodestring() error 79 80 raise cherrypy.HTTPError(400, 'Bad Request') 80 81 81 82 # Respond with 401 status and a WWW-Authenticate header 82 cherrypy. response.headers['www-authenticate'] = 'Basic realm="%s"' % realm83 cherrypy.serving.response.headers['www-authenticate'] = 'Basic realm="%s"' % realm 83 84 raise cherrypy.HTTPError(401, "You are not authorized to access that resource") 84 85 branches/python3/cherrypy/lib/auth_digest.py
r2420 r2461 308 308 Arguments: 309 309 realm: a string containing the authentication realm. 310 310 311 311 get_ha1: a callable which looks up a username in a credentials store 312 312 and returns the HA1 string, which is defined in the RFC to be … … 316 316 If username is not found in the credentials store, get_ha1() returns 317 317 None. 318 318 319 319 key: a secret string known only to the server, used in the synthesis of nonces. 320 320 """ 321 322 auth_header = cherrypy.request.headers.get('authorization') 321 request = cherrypy.serving.request 322 323 auth_header = request.headers.get('authorization') 323 324 nonce_is_stale = False 324 325 if auth_header is not None: 325 326 try: 326 auth = HttpDigestAuthorization(auth_header, cherrypy.request.method, debug=debug)327 auth = HttpDigestAuthorization(auth_header, request.method, debug=debug) 327 328 except ValueError as e: 328 329 raise cherrypy.HTTPError(400, 'Bad Request: %s' % e) 329 330 330 331 if debug: 331 332 TRACE(str(auth)) 332 333 333 334 if auth.validate_nonce(realm, key): 334 335 ha1 = get_ha1(realm, auth.username) … … 336 337 # note that for request.body to be available we need to hook in at 337 338 # before_handler, not on_start_resource like 3.1.x digest_auth does. 338 digest = auth.request_digest(ha1, entity_body= cherrypy.request.body)339 digest = auth.request_digest(ha1, entity_body=request.body) 339 340 if digest == auth.response: # authenticated 340 341 if debug: … … 344 345 nonce_is_stale = auth.is_nonce_stale(max_age_seconds=600) 345 346 if not nonce_is_stale: 346 cherrypy.request.login = auth.username347 request.login = auth.username 347 348 if debug: 348 349 TRACE("authentication of %s successful" % auth.username) 349 350 return 350 351 351 352 # Respond with 401 status and a WWW-Authenticate header 352 353 header = www_authenticate(realm, key, stale=nonce_is_stale) 353 354 if debug: 354 355 TRACE(header) 355 cherrypy. response.headers['WWW-Authenticate'] = header356 cherrypy.serving.response.headers['WWW-Authenticate'] = header 356 357 raise cherrypy.HTTPError(401, "You are not authorized to access that resource") 357 358 branches/python3/cherrypy/lib/caching.py
r2455 r2461 124 124 125 125 def key(self): 126 request = cherrypy. request126 request = cherrypy.serving.request 127 127 try: 128 response = cherrypy. response128 response = cherrypy.serving.response 129 129 except AttributeError: 130 130 response = None … … 172 172 if (obj_size < self.maxobj_size and total_size < self.maxsize): 173 173 # add to the expirations list and cache 174 expiration_time = cherrypy. response.time + self.delay174 expiration_time = cherrypy.serving.response.time + self.delay 175 175 obj_key = self.key() 176 176 bucket = self.expirations.setdefault(expiration_time, []) … … 207 207 * returns False 208 208 """ 209 request = cherrypy.request 209 request = cherrypy.serving.request 210 response = cherrypy.serving.response 210 211 211 212 # POST, PUT, DELETE should invalidate (delete) the cached copy. … … 221 222 request.cacheable = not c 222 223 if c: 223 response = cherrypy.response224 224 s, h, b, create_time, original_req_headers = cache_data 225 225 … … 260 260 # save the cache data 261 261 body = b''.join(output) 262 vary = [he.value for he in 263 cherrypy.response.headers.elements('Vary')] 262 vary = [he.value for he in response.headers.elements('Vary')] 264 263 sel_headers = dict([(k, v) for k, v 265 in cherrypy. request.headers.items()264 in cherrypy.serving.request.headers.items() 266 265 if k in vary]) 267 266 cherrypy._cache.put((response.status, response.headers or {}, 268 267 body, response.time, sel_headers)) 269 268 270 response = cherrypy. response269 response = cherrypy.serving.response 271 270 response.body = tee(response.body) 272 271 … … 289 288 """ 290 289 291 response = cherrypy. response290 response = cherrypy.serving.response 292 291 headers = response.headers 293 292 … … 307 306 if force or "Pragma" not in headers: 308 307 headers["Pragma"] = "no-cache" 309 if cherrypy. request.protocol >= (1, 1):308 if cherrypy.serving.request.protocol >= (1, 1): 310 309 if force or "Cache-Control" not in headers: 311 310 headers["Cache-Control"] = "no-cache, must-revalidate" branches/python3/cherrypy/lib/cptools.py
r2412 r2461 31 31 See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24 32 32 """ 33 response = cherrypy. response33 response = cherrypy.serving.response 34 34 35 35 # Guard against being run twice. … … 54 54 # MUST be ignored." 55 55 if status >= 200 and status <= 299: 56 request = cherrypy. request56 request = cherrypy.serving.request 57 57 58 58 conditions = request.headers.elements('If-Match') or [] … … 77 77 will be performed. 78 78 """ 79 response = cherrypy. response79 response = cherrypy.serving.response 80 80 lastmod = response.headers.get('Last-Modified') 81 81 if lastmod: 82 82 status, reason, msg = _httputil.valid_status(response.status) 83 83 84 request = cherrypy. request84 request = cherrypy.serving.request 85 85 86 86 since = request.headers.get('If-Unmodified-Since') … … 118 118 """ 119 119 120 request = cherrypy. request120 request = cherrypy.serving.request 121 121 122 122 if scheme: … … 134 134 base = request.headers.get(local, base) 135 135 if not base: 136 port = cherrypy.request.local.port136 port = request.local.port 137 137 if port == 80: 138 138 base = '127.0.0.1' … … 162 162 headers, and will doubly-truncate the response. 163 163 """ 164 request = cherrypy. request164 request = cherrypy.serving.request 165 165 for name in headers: 166 166 if name in request.headers: … … 171 171 """Set headers on the response.""" 172 172 for name, value in (headers or []): 173 cherrypy. response.headers[name] = value173 cherrypy.serving.response.headers[name] = value 174 174 response_headers.failsafe = True 175 175 … … 187 187 """ 188 188 try: 189 match = bool(re.match(pattern, cherrypy. request.headers['Referer']))189 match = bool(re.match(pattern, cherrypy.serving.request.headers['Referer'])) 190 190 if accept == match: 191 191 return … … 232 232 def do_login(self, username, password, from_page='..', **kwargs): 233 233 """Login. May raise redirect, or return True if request handled.""" 234 response = cherrypy.serving.response 234 235 error_msg = self.check_username_and_password(username, password) 235 236 if error_msg: 236 237 body = self.login_screen(from_page, username, error_msg) 237 cherrypy.response.body = body238 if "Content-Length" in cherrypy.response.headers:238 response.body = body 239 if "Content-Length" in response.headers: 239 240 # Delete Content-Length header so finalize() recalcs it. 240 del cherrypy.response.headers["Content-Length"]241 del response.headers["Content-Length"] 241 242 return True 242 243 else: 243 cherrypy.session[self.session_key] = cherrypy.request.login = username 244 cherrypy.serving.request.login = username 245 cherrypy.session[self.session_key] = username 244 246 self.on_login(username) 245 247 raise cherrypy.HTTPRedirect(from_page or "/") … … 251 253 sess[self.session_key] = None 252 254 if username: 253 cherrypy. request.login = None255 cherrypy.serving.request.login = None 254 256 self.on_logout(username) 255 257 raise cherrypy.HTTPRedirect(from_page) … … 258 260 """Assert username. May raise redirect, or return True if request handled.""" 259 261 sess = cherrypy.session 260 request = cherrypy.request 262 request = cherrypy.serving.request 263 response = cherrypy.serving.response 261 264 262 265 username = sess.get(self.session_key) … … 264 267 sess[self.session_key] = username = self.anonymous() 265 268 if not username: 266 cherrypy.response.body = self.login_screen(cherrypy.url(qs=request.query_string))267 if "Content-Length" in cherrypy.response.headers:269 response.body = self.login_screen(cherrypy.url(qs=request.query_string)) 270 if "Content-Length" in response.headers: 268 271 # Delete Content-Length header so finalize() recalcs it. 269 del cherrypy.response.headers["Content-Length"]272 del response.headers["Content-Length"] 270 273 return True 271 cherrypy.request.login = username274 request.login = username 272 275 self.on_check(username) 273 276 274 277 def run(self): 275 request = cherrypy.request 278 request = cherrypy.serving.request 279 response = cherrypy.serving.response 280 276 281 path = request.path_info 277 282 if path.endswith('login_screen'): … … 279 284 elif path.endswith('do_login'): 280 285 if request.method != 'POST': 281 cherrypy.response.headers['Allow'] = "POST"286 response.headers['Allow'] = "POST" 282 287 raise cherrypy.HTTPError(405) 283 288 return self.do_login(**request.params) 284 289 elif path.endswith('do_logout'): 285 290 if request.method != 'POST': 286 cherrypy.response.headers['Allow'] = "POST"291 response.headers['Allow'] = "POST" 287 292 raise cherrypy.HTTPError(405) 288 293 return self.do_logout(**request.params) … … 311 316 def log_request_headers(): 312 317 """Write request headers to the cherrypy error log.""" 313 h = [" %s: %s" % (k, v) for k, v in cherrypy. request.header_list]318 h = [" %s: %s" % (k, v) for k, v in cherrypy.serving.request.header_list] 314 319 cherrypy.log('\nRequest Headers:\n' + '\n'.join(h), "HTTP") 315 320 316 321 def log_hooks(): 317 322 """Write request.hooks to the cherrypy error log.""" 323 request = cherrypy.serving.request 324 318 325 msg = [] 319 326 # Sort by the standard points if possible. 320 327 from cherrypy import _cprequest 321 328 points = _cprequest.hookpoints 322 for k in cherrypy.request.hooks.keys():329 for k in request.hooks.keys(): 323 330 if k not in points: 324 331 points.append(k) … … 326 333 for k in points: 327 334 msg.append(" %s:" % k) 328 v = cherrypy.request.hooks.get(k, [])335 v = request.hooks.get(k, []) 329 336 v.sort() 330 337 for h in v: … … 342 349 def trailing_slash(missing=True, extra=False, status=None): 343 350 """Redirect if path_info has (missing|extra) trailing slash.""" 344 request = cherrypy. request351 request = cherrypy.serving.request 345 352 pi = request.path_info 346 353 … … 371 378 for y in flattener(x): 372 379 yield y 373 response = cherrypy. response380 response = cherrypy.serving.response 374 381 response.body = flattener(response.body) 375 382 … … 403 410 if isinstance(media, str): 404 411 media = [media] 412 request = cherrypy.serving.request 405 413 406 414 # Parse the Accept request header, and try to match one 407 415 # of the requested media-ranges (in order of preference). 408 ranges = cherrypy.request.headers.elements('Accept')416 ranges = request.headers.elements('Accept') 409 417 if not ranges: 410 418 # Any media type is acceptable. … … 429 437 430 438 # No suitable media-range found. 431 ah = cherrypy.request.headers.get('Accept')439 ah = request.headers.get('Accept') 432 440 if ah is None: 433 441 msg = "Your client did not send an Accept header." … … 459 467 def autovary(ignore=None): 460 468 """Auto-populate the Vary response header based on request.header access.""" 461 req_h = cherrypy.request.headers 462 cherrypy.request.headers = MonitoredHeaderMap() 463 cherrypy.request.headers.update(req_h) 469 request = cherrypy.serving.request 470 471 req_h = request.headers 472 request.headers = MonitoredHeaderMap() 473 request.headers.update(req_h) 464 474 if ignore is None: 465 475 ignore = set(['Content-Disposition', 'Content-Length', 'Content-Type']) 466 476 467 477 def set_response_header(): 468 resp_h = cherrypy. response.headers478 resp_h = cherrypy.serving.response.headers 469 479 v = set([e.value for e in resp_h.elements('Vary')]) 470 v = v.union( cherrypy.request.headers.accessed_headers)480 v = v.union(request.headers.accessed_headers) 471 481 v = v.difference(ignore) 472 482 v = list(v) 473 483 v.sort() 474 484 resp_h['Vary'] = ', '.join(v) 475 cherrypy.request.hooks.attach(485 request.hooks.attach( 476 486 'before_finalize', set_response_header, 95) 477 487 478 488 489 branches/python3/cherrypy/lib/encoding.py
r2438 r2461 22 22 23 23 self.attempted_charsets = set() 24 25 if cherrypy.request.handler is not None:24 request = cherrypy.serving.request 25 if request.handler is not None: 26 26 # Replace request.handler with self 27 self.oldhandler = cherrypy.request.handler28 cherrypy.request.handler = self27 self.oldhandler = request.handler 28 request.handler = self 29 29 30 30 def encode_stream(self, encoding): … … 65 65 66 66 def find_acceptable_charset(self): 67 response = cherrypy.response 68 69 if cherrypy.response.stream: 67 request = cherrypy.serving.request 68 response = cherrypy.serving.response 69 70 if response.stream: 70 71 encoder = self.encode_stream 71 72 else: … … 86 87 # Parse the Accept-Charset request header, and try to provide one 87 88 # of the requested charsets (in order of user preference). 88 encs = cherrypy.request.headers.elements('Accept-Charset')89 encs = request.headers.elements('Accept-Charset') 89 90 charsets = [enc.value.lower() for enc in encs] 90 91 … … 125 126 126 127 # No suitable encoding found. 127 ac = cherrypy.request.headers.get('Accept-Charset')128 ac = request.headers.get('Accept-Charset') 128 129 if ac is None: 129 130 msg = "Your client did not send an Accept-Charset header." … … 134 135 135 136 def __call__(self, *args, **kwargs): 137 response = cherrypy.serving.response 136 138 self.body = self.oldhandler(*args, **kwargs) 137 139 … … 150 152 self.body = [] 151 153 152 ct = cherrypy.response.headers.elements("Content-Type")154 ct = response.headers.elements("Content-Type") 153 155 if ct: 154 156 ct = ct[0] … … 157 159 ct.params['charset'] = self.find_acceptable_charset() 158 160 if self.add_charset: 159 cherrypy.response.headers["Content-Type"] = str(ct)161 response.headers["Content-Type"] = str(ct) 160 162 161 163 return self.body … … 216 218 * The 'identity' value is given with a qvalue > 0. 217 219 """ 218 response = cherrypy.response 220 request = cherrypy.serving.request 221 response = cherrypy.serving.response 219 222 220 223 set_vary_header(response, "Accept-Encoding") … … 226 229 # If returning cached content (which should already have been gzipped), 227 230 # don't re-zip. 228 if getattr( cherrypy.request, "cached", False):231 if getattr(request, "cached", False): 229 232 return 230 233 231 acceptable = cherrypy.request.headers.elements('Accept-Encoding')234 acceptable = request.headers.elements('Accept-Encoding') 232 235 if not acceptable: 233 236 # If no Accept-Encoding field is present in a request, branches/python3/cherrypy/lib/jsontools.py
r2388 r2461 8 8 9 9 def json_in(*args, **kwargs): 10 request = cherrypy. request10 request = cherrypy.serving.request 11 11 _h = request.headers 12 12 if ('Content-Type' not in _h … … 25 25 26 26 def json_out(*args, **kwargs): 27 request = cherrypy. request28 response = cherrypy. response27 request = cherrypy.serving.request 28 response = cherrypy.serving.response 29 29 30 30 real_handler = request.handler branches/python3/cherrypy/lib/sessions.py
r2441 r2461 562 562 if not hasattr(cherrypy.serving, "session"): 563 563 return 564 request = cherrypy.serving.request 565 response = cherrypy.serving.response 564 566 565 567 # Guard against running twice 566 if hasattr( cherrypy.request, "_sessionsaved"):568 if hasattr(request, "_sessionsaved"): 567 569 return 568 cherrypy.request._sessionsaved = True569 570 if cherrypy.response.stream:570 request._sessionsaved = True 571 572 if response.stream: 571 573 # If the body is being streamed, we have to save the data 572 574 # *after* the response has been written out 573 cherrypy.request.hooks.attach('on_end_request', cherrypy.session.save)575 request.hooks.attach('on_end_request', cherrypy.session.save) 574 576 else: 575 577 # If the body is not being streamed, we save the data now 576 578 # (so we can release the lock). 577 if isinstance( cherrypy.response.body, types.GeneratorType):578 cherrypy.response.collapse_body()579 if isinstance(response.body, types.GeneratorType): 580 response.collapse_body() 579 581 cherrypy.session.save() 580 582 save.failsafe = True … … 619 621 """ 620 622 621 request = cherrypy. request623 request = cherrypy.serving.request 622 624 623 625 # Guard against running twice … … 646 648 def update_cookie(id): 647 649 """Update the cookie every time the session id changes.""" 648 cherrypy. response.cookie[name] = id650 cherrypy.serving.response.cookie[name] = id 649 651 sess.id_observers.append(update_cookie) 650 652 … … 679 681 """ 680 682 # Set response cookie 681 cookie = cherrypy. response.cookie683 cookie = cherrypy.serving.response.cookie 682 684 cookie[name] = cherrypy.serving.session.id 683 cookie[name]['path'] = (path or cherrypy. request.headers.get(path_header)685 cookie[name]['path'] = (path or cherrypy.serving.request.headers.get(path_header) 684 686 or '/') 685 687 … … 700 702 def expire(): 701 703 """Expire the current session cookie.""" 702 name = cherrypy. request.config.get('tools.sessions.name', 'session_id')704 name = cherrypy.serving.request.config.get('tools.sessions.name', 'session_id') 703 705 one_year = 60 * 60 * 24 * 365 704 706 e = time.time() - one_year 705 cherrypy. response.cookie[name]['expires'] = httputil.HTTPDate(e)706 707 707 cherrypy.serving.response.cookie[name]['expires'] = httputil.HTTPDate(e) 708 709 branches/python3/cherrypy/lib/static.py
r2420 r2461 31 31 """ 32 32 33 response = cherrypy. response33 response = cherrypy.serving.response 34 34 35 35 # If path is relative, users should fix it by making path absolute. … … 87 87 not be set. If disposition is None, no Content-Disposition header will 88 88 be written. 89 """ 90 91 response = cherrypy.response 89 90 CAUTION: If the request contains a 'Range' header, one or more seek()s will 91 be performed on the file object. This may cause undesired behavior if 92 the file object is not seekable. It could also produce undesired results 93 if the caller set the read position of the file object prior to calling 94 serve_fileobj(), expecting that the data would be served starting from that 95 position. 96 """ 97 98 response = cherrypy.serving.response 92 99 93 100 try: … … 116 123 def _serve_fileobj(fileobj, content_type, content_length): 117 124 """Internal. Set response.body to the given file object, perhaps ranged.""" 118 response = cherrypy. response125 response = cherrypy.serving.response 119 126 120 127 # HTTP/1.0 didn't have Range/Accept-Ranges headers, or the 206 code 121 if cherrypy.request.protocol >= (1, 1): 128 request = cherrypy.serving.request 129 if request.protocol >= (1, 1): 122 130 response.headers["Accept-Ranges"] = "bytes" 123 r = httputil.get_ranges(cherrypy.request.headers.get('Range'), 124 content_length) 131 r = httputil.get_ranges(request.headers.get('Range'), content_length) 125 132 if r == []: 126 133 response.headers['Content-Range'] = "bytes */%s" % content_length … … 216 223 'index.html', the file '/home/me/myapp/index.html' will be sought. 217 224 """ 218 if cherrypy.request.method not in ('GET', 'HEAD'): 219 return False 220 221 if match and not re.search(match, cherrypy.request.path_info): 225 request = cherrypy.serving.request 226 if request.method not in ('GET', 'HEAD'): 227 return False 228 229 if match and not re.search(match, request.path_info): 222 230 return False 223 231 … … 237 245 section = "/" 238 246 section = section.rstrip(r"\/") 239 branch = cherrypy.request.path_info[len(section) + 1:]247 branch = request.path_info[len(section) + 1:] 240 248 branch = unquote(branch.lstrip(r"\/")) 241 249 … … 243 251 filename = os.path.join(dir, branch) 244 252 cherrypy.log('Checking file %r to fulfill %r' % 245 (filename, cherrypy.request.path_info),253 (filename, request.path_info), 246 254 context='tools.staticdir', severity=logging.DEBUG) 247 255 … … 258 266 handled = _attempt(os.path.join(filename, index), content_types) 259 267 if handled: 260 cherrypy.request.is_index = filename[-1] in (r"\/")268 request.is_index = filename[-1] in (r"\/") 261 269 return handled 262 270 … … 272 280 out in the Content-Type response header (e.g. "image/gif"). 273 281 """ 274 if cherrypy.request.method not in ('GET', 'HEAD'): 275 return False 276 277 if match and not re.search(match, cherrypy.request.path_info): 282 request = cherrypy.serving.request 283 if request.method not in ('GET', 'HEAD'): 284 return False 285 286 if match and not re.search(match, request.path_info): 278 287 return False 279 288 branches/python3/cherrypy/process/wspbus.py
r2401 r2461 218 218 self.log("Shutting down due to error in start listener:", 219 219 level=40, traceback=True) 220 e_info = sys.exc_info()221 220 try: 222 221 self.exit() branches/python3/cherrypy/test/benchmark.py
r2438 r2461 188 188 189 189 parse_patterns = [('complete_requests', 'Completed', 190 r'^Complete requests:\s*(\d+)'),190 br'^Complete requests:\s*(\d+)'), 191 191 ('failed_requests', 'Failed', 192 r'^Failed requests:\s*(\d+)'),192 br'^Failed requests:\s*(\d+)'), 193 193 ('requests_per_second', 'req/sec', 194 r'^Requests per second:\s*([0-9.]+)'),194 br'^Requests per second:\s*([0-9.]+)'), 195 195 ('time_per_request_concurrent', 'msec/req', 196 r'^Time per request:\s*([0-9.]+).*concurrent requests\)$'),196 br'^Time per request:\s*([0-9.]+).*concurrent requests\)$'), 197 197 ('transfer_rate', 'KB/sec', 198 r'^Transfer rate:\s*([0-9.]+)'),198 br'^Transfer rate:\s*([0-9.]+)'), 199 199 ] 200 200 … … 247 247 row = [c] 248 248 for attr in attrs: 249 val = getattr(sess, attr)249 val = float(getattr(sess, attr)) 250 250 avg[attr] += float(val) 251 251 row.append(val) … … 378 378 print("\nUsing null Request object") 379 379 try: 380 run_standard_benchmarks() 380 try: 381 run_standard_benchmarks() 382 except: 383 print(_cperror.format_exc()) 384 raise 381 385 finally: 382 386 cherrypy.engine.exit() branches/python3/cherrypy/test/test.py
r2438 r2461 153 153 warnings.warn("Error importing wsgiconq. pyconquer will not run.") 154 154 else: 155 app = wsgiconq.WSGILogger(app )155 app = wsgiconq.WSGILogger(app, c_calls=True) 156 156 if self.validate: 157 157 try: branches/python3/cherrypy/test/test_dynamicobjectmapping.py
r2274 r2461 4 4 5 5 import cherrypy 6 7 6 8 7 script_names = ["", "/foo", "/users/fred/blog", "/corp/blog"]

