Changeset 382
- Timestamp:
- 06/25/05 15:37:39
- Files:
-
- trunk/cherrypy/__init__.py (modified) (1 diff)
- trunk/cherrypy/_cperror.py (moved) (moved from trunk/cherrypy/cperror.py) (8 diffs)
- trunk/cherrypy/_cphttpserver.py (modified) (10 diffs)
- trunk/cherrypy/_cphttptools.py (modified) (25 diffs)
- trunk/cherrypy/_cputil.py (modified) (10 diffs)
- trunk/cherrypy/_cpwsgi.py (modified) (5 diffs)
- trunk/cherrypy/_cpwsgiserver.py (modified) (1 diff)
- trunk/cherrypy/config.py (moved) (moved from trunk/cherrypy/_cpconfig.py) (7 diffs)
- trunk/cherrypy/cpg.py (deleted)
- trunk/cherrypy/lib/cptools.py (modified) (4 diffs)
- trunk/cherrypy/lib/csauthenticate.py (modified) (6 diffs)
- trunk/cherrypy/lib/filter/baseurlfilter.py (modified) (2 diffs)
- trunk/cherrypy/lib/filter/cachefilter.py (modified) (3 diffs)
- trunk/cherrypy/lib/filter/decodingfilter.py (modified) (2 diffs)
- trunk/cherrypy/lib/filter/encodingfilter.py (modified) (2 diffs)
- trunk/cherrypy/lib/filter/gzipfilter.py (modified) (1 diff)
- trunk/cherrypy/lib/filter/logdebuginfofilter.py (modified) (4 diffs)
- trunk/cherrypy/lib/filter/nsgmlsfilter.py (modified) (6 diffs)
- trunk/cherrypy/lib/filter/sessionauthenticatefilter.py (modified) (4 diffs)
- trunk/cherrypy/lib/filter/sessionfilter/__init__.py (modified) (1 diff)
- trunk/cherrypy/lib/filter/sessionfilter/basesession.py (modified) (7 diffs)
- trunk/cherrypy/lib/filter/sessionfilter/basesessiondict.py (modified) (2 diffs)
- trunk/cherrypy/lib/filter/sessionfilter/dbmsession.py (modified) (2 diffs)
- trunk/cherrypy/lib/filter/sessionfilter/filesession.py (modified) (2 diffs)
- trunk/cherrypy/lib/filter/sessionfilter/ramsession.py (modified) (1 diff)
- trunk/cherrypy/lib/filter/sessionfilter/sessionconfig.py (modified) (1 diff)
- trunk/cherrypy/lib/filter/sessionfilter/sessionfilter.py (deleted)
- trunk/cherrypy/lib/filter/sessionfilter/sqlobjectsession.py (modified) (4 diffs)
- trunk/cherrypy/lib/filter/staticfilter.py (modified) (1 diff)
- trunk/cherrypy/lib/filter/tidyfilter.py (modified) (8 diffs)
- trunk/cherrypy/lib/filter/virtualhostfilter.py (modified) (1 diff)
- trunk/cherrypy/lib/filter/xmlrpcfilter.py (modified) (7 diffs)
- trunk/cherrypy/lib/form.py (modified) (1 diff)
- trunk/cherrypy/lib/httptools.py (modified) (1 diff)
- trunk/cherrypy/lib/profiler.py (modified) (3 diffs)
- trunk/cherrypy/server.py (moved) (moved from trunk/cherrypy/_cpserver.py) (8 diffs)
- trunk/cherrypy/test/helper.py (modified) (6 diffs)
- trunk/cherrypy/test/test.py (modified) (3 diffs)
- trunk/cherrypy/test/test_baseurl_filter.py (modified) (3 diffs)
- trunk/cherrypy/test/test_cache_filter.py (modified) (2 diffs)
- trunk/cherrypy/test/test_combinedfilters.py (modified) (4 diffs)
- trunk/cherrypy/test/test_core.py (modified) (16 diffs)
- trunk/cherrypy/test/test_decodingencoding_filter.py (modified) (4 diffs)
- trunk/cherrypy/test/test_gzip_filter.py (modified) (4 diffs)
- trunk/cherrypy/test/test_logdebuginfo_filter.py (modified) (4 diffs)
- trunk/cherrypy/test/test_noserver.py (modified) (2 diffs)
- trunk/cherrypy/test/test_objectmapping.py (modified) (6 diffs)
- trunk/cherrypy/test/test_static_filter.py (modified) (3 diffs)
- trunk/cherrypy/test/test_tutorials.py (modified) (10 diffs)
- trunk/cherrypy/test/test_virtualhost_filter.py (modified) (4 diffs)
- trunk/cherrypy/tutorial/bonus-sqlobject.py (modified) (2 diffs)
- trunk/cherrypy/tutorial/tut01_helloworld.py (modified) (2 diffs)
- trunk/cherrypy/tutorial/tut02_expose_methods.py (modified) (2 diffs)
- trunk/cherrypy/tutorial/tut03_get_and_post.py (modified) (2 diffs)
- trunk/cherrypy/tutorial/tut04_complex_site.py (modified) (3 diffs)
- trunk/cherrypy/tutorial/tut05_derived_objects.py (modified) (2 diffs)
- trunk/cherrypy/tutorial/tut06_default_method.py (modified) (3 diffs)
- trunk/cherrypy/tutorial/tut07_sessions.py (modified) (4 diffs)
- trunk/cherrypy/tutorial/tut08_generators_and_yield.py (modified) (2 diffs)
- trunk/cherrypy/tutorial/tut09_sessionfilter.py (modified) (6 diffs)
- trunk/cherrypy/tutorial/tut10_file_upload.py (modified) (2 diffs)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
trunk/cherrypy/__init__.py
r310 r382 1 """ 2 Copyright (c) 2004, CherryPy Team (team@cherrypy.org) 3 All rights reserved. 4 5 Redistribution and use in source and binary forms, with or without modification, 6 are permitted provided that the following conditions are met: 7 8 * Redistributions of source code must retain the above copyright notice, 9 this list of conditions and the following disclaimer. 10 * Redistributions in binary form must reproduce the above copyright notice, 11 this list of conditions and the following disclaimer in the documentation 12 and/or other materials provided with the distribution. 13 * Neither the name of the CherryPy Team nor the names of its contributors 14 may be used to endorse or promote products derived from this software 15 without specific prior written permission. 16 17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 18 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 19 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 20 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 21 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 23 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 24 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 25 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 26 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 """ 28 29 """ 30 Global module that all modules developing with CherryPy should import. 31 """ 32 1 33 __version__ = '2.1.0 alpha' 34 35 from _cperror import * 36 37 import config 38 import server 39 40 _httpserver = None 41 42 # decorator function for exposing methods 43 def expose(func): 44 func.exposed = True 45 return func 46 47 def log(msg, context='', severity=0): 48 """Syntactic sugar for writing to the log.""" 49 import _cputil 50 logfunc = _cputil.getSpecialAttribute('_cpLogMessage') 51 logfunc(msg, context, severity) 52 trunk/cherrypy/_cperror.py
r380 r382 40 40 41 41 class WrongResponseType(Error): 42 """ Happens when the c pg.response.body is not a string """42 """ Happens when the cherrypy.response.body is not a string """ 43 43 pass 44 44 … … 65 65 66 66 def __init__(self, path, queryString=None): 67 from cherrypy import cpg67 import cherrypy 68 68 import cgi 69 69 70 70 self.path = path 71 71 if queryString is not None: 72 c pg.request.queryString = queryString72 cherrypy.request.queryString = queryString 73 73 74 pm = cgi.parse_qs(c pg.request.queryString, keep_blank_values=True)74 pm = cgi.parse_qs(cherrypy.request.queryString, keep_blank_values=True) 75 75 for key, val in pm.items(): 76 76 if len(val) == 1: 77 77 pm[key] = val[0] 78 c pg.request.paramMap = pm78 cherrypy.request.paramMap = pm 79 79 80 c pg.request.browserUrl = cpg.request.base + path80 cherrypy.request.browserUrl = cherrypy.request.base + path 81 81 82 82 … … 91 91 def __init__(self, urls, status=None): 92 92 import urlparse 93 from cherrypy import cpg93 import cherrypy 94 94 95 95 if isinstance(urls, basestring): … … 99 99 for url in urls: 100 100 if url.startswith("/"): 101 url = urlparse.urljoin(c pg.request.base, url)101 url = urlparse.urljoin(cherrypy.request.base, url) 102 102 abs_urls.append(url) 103 103 self.urls = abs_urls … … 107 107 # http://ppewww.ph.gla.ac.uk/~flavell/www/post-redirect.html 108 108 if status is None: 109 if c pg.request.protocol == "HTTP/1.1":109 if cherrypy.request.protocol == "HTTP/1.1": 110 110 status = 303 111 111 else: … … 119 119 120 120 def set_response(self): 121 import c pg122 c pg.response.status = status = self.status123 c pg.response.headerMap['Content-Type'] = "text/html"121 import cherrypy 122 cherrypy.response.status = status = self.status 123 cherrypy.response.headerMap['Content-Type'] = "text/html" 124 124 125 125 if status in (300, 301, 302, 303, 307): 126 126 # "The ... URI SHOULD be given by the Location field 127 127 # in the response." 128 c pg.response.headerMap['Location'] = self.urls[0]128 cherrypy.response.headerMap['Location'] = self.urls[0] 129 129 130 130 # "Unless the request method was HEAD, the entity of the response … … 137 137 307: "This resource has moved temporarily to <a href='%s'>%s</a>.", 138 138 }[status] 139 c pg.response.body = "<br />\n".join([msg % (url, url)139 cherrypy.response.body = "<br />\n".join([msg % (url, url) 140 140 for url in self.urls]) 141 141 elif status == 304: … … 146 146 147 147 # "The 304 response MUST NOT contain a message-body." 148 c pg.response.body = []148 cherrypy.response.body = [] 149 149 elif status == 305: 150 150 # Use Proxy. 151 151 # self.urls[0] should be the URI of the proxy. 152 c pg.response.headerMap['Location'] = self.urls[0]153 c pg.response.body = []152 cherrypy.response.headerMap['Location'] = self.urls[0] 153 cherrypy.response.body = [] 154 154 else: 155 155 raise ValueError("The %s status code is unknown." % status) trunk/cherrypy/_cphttpserver.py
r357 r382 28 28 29 29 import threading, SocketServer, BaseHTTPServer, socket, Queue 30 import cpg, _cpserver, _cphttptools 30 import cherrypy 31 from cherrypy import _cphttptools 31 32 32 33 try: … … 49 50 def address_string(self): 50 51 """ Try to do a reverse DNS based on [server]reverseDNS in the config file """ 51 if c pg.config.get('server.reverseDNS'):52 if cherrypy.config.get('server.reverseDNS'): 52 53 return BaseHTTPServer.BaseHTTPRequestHandler.address_string(self) 53 54 else: … … 80 81 return 81 82 82 c pg.request.multithread = cpg.config.get("server.threadPool") > 183 c pg.request.multiprocess = False84 _cpserver.request(self.client_address[0],85 self.address_string(),86 self.raw_requestline,87 self._headerlist(),88 self.rfile)83 cherrypy.request.multithread = cherrypy.config.get("server.threadPool") > 1 84 cherrypy.request.multiprocess = False 85 cherrypy.server.request(self.client_address[0], 86 self.address_string(), 87 self.raw_requestline, 88 self._headerlist(), 89 self.rfile) 89 90 wfile = self.wfile 90 wfile.write("%s %s\r\n" % (self.protocol_version, c pg.response.status))91 92 for name, value in c pg.response.headers:91 wfile.write("%s %s\r\n" % (self.protocol_version, cherrypy.response.status)) 92 93 for name, value in cherrypy.response.headers: 93 94 wfile.write("%s: %s\r\n" % (name, value)) 94 95 95 96 wfile.write("\r\n") 96 97 try: 97 for chunk in c pg.response.body:98 for chunk in cherrypy.response.body: 98 99 wfile.write(chunk) 99 100 except: … … 107 108 def log_message(self, format, *args): 108 109 """ We have to override this to use our own logging mechanism """ 109 c pg.log(format % args, "HTTP")110 cherrypy.log(format % args, "HTTP") 110 111 111 112 … … 141 142 return 1 142 143 except (KeyboardInterrupt, SystemExit): 143 c pg.log("<Ctrl-C> hit: shutting down http server", "HTTP")144 cherrypy.log("<Ctrl-C> hit: shutting down http server", "HTTP") 144 145 self.shutdown() 145 146 … … 195 196 """Handle an error gracefully. May be overridden.""" 196 197 errorBody = _cphttptools.formatExc() 197 c pg.log(errorBody)198 cherrypy.log(errorBody) 198 199 199 200 … … 273 274 request, client_address = self.get_request() 274 275 except (KeyboardInterrupt, SystemExit): 275 c pg.log("<Ctrl-C> hit: shutting down", "HTTP")276 cherrypy.log("<Ctrl-C> hit: shutting down", "HTTP") 276 277 return 0 277 278 except socket.error, e: … … 296 297 297 298 # Set protocol_version 298 proto = c pg.config.get('server.protocolVersion')299 proto = cherrypy.config.get('server.protocolVersion') 299 300 if not proto: 300 301 proto = "HTTP/1.0" … … 302 303 303 304 # Select the appropriate server based on config options 304 sockFile = c pg.config.get('server.socketFile')305 threadPool = c pg.config.get('server.threadPool')305 sockFile = cherrypy.config.get('server.socketFile') 306 threadPool = cherrypy.config.get('server.threadPool') 306 307 if sockFile: 307 308 # AF_UNIX socket … … 320 321 else: 321 322 ServerClass = CherryHTTPServer 322 server_address = (c pg.config.get('server.socketHost'),323 c pg.config.get('server.socketPort'))324 325 ServerClass.request_queue_size = c pg.config.get('server.socketQueueSize')323 server_address = (cherrypy.config.get('server.socketHost'), 324 cherrypy.config.get('server.socketPort')) 325 326 ServerClass.request_queue_size = cherrypy.config.get('server.socketQueueSize') 326 327 327 328 if handler is None: trunk/cherrypy/_cphttptools.py
r376 r382 35 35 from lib.filter import basefilter 36 36 37 import cpg, _cputil, cperror, _cpcgifs 37 import cherrypy 38 from cherrypy import _cputil, _cpcgifs 38 39 39 40 # Can't use cStringIO; doesn't support unicode strings … … 106 107 107 108 def __init__(self, clientAddress, remoteHost, requestLine, headers, rfile): 108 # When __init__ is finished, c pg.response should have three attributes:109 # When __init__ is finished, cherrypy.response should have three attributes: 109 110 # status, e.g. "200 OK" 110 111 # headers, a list of (name, value) tuples … … 116 117 self.requestHeaders = headers 117 118 118 # Prepare c pg.request variables119 c pg.request.remoteAddr = clientAddress120 c pg.request.remoteHost = remoteHost121 c pg.request.paramList = [] # Only used for Xml-Rpc122 c pg.request.headerMap = {}123 c pg.request.requestLine = requestLine124 c pg.request.simpleCookie = Cookie.SimpleCookie()125 c pg.request.rfile = rfile126 127 # Prepare c pg.response variables128 c pg.response.status = None129 c pg.response.headers = None130 c pg.response.body = None119 # Prepare cherrypy.request variables 120 cherrypy.request.remoteAddr = clientAddress 121 cherrypy.request.remoteHost = remoteHost 122 cherrypy.request.paramList = [] # Only used for Xml-Rpc 123 cherrypy.request.headerMap = {} 124 cherrypy.request.requestLine = requestLine 125 cherrypy.request.simpleCookie = Cookie.SimpleCookie() 126 cherrypy.request.rfile = rfile 127 128 # Prepare cherrypy.response variables 129 cherrypy.response.status = None 130 cherrypy.response.headers = None 131 cherrypy.response.body = None 131 132 132 133 year, month, day, hh, mm, ss, wd, y, z = time.gmtime() 133 134 date = ("%s, %02d %3s %4d %02d:%02d:%02d GMT" % 134 135 (weekdayname[wd], day, monthname[month], year, hh, mm, ss)) 135 c pg.response.headerMap = KeyTitlingDict()136 c pg.response.headerMap.update({136 cherrypy.response.headerMap = KeyTitlingDict() 137 cherrypy.response.headerMap.update({ 137 138 "Content-Type": "text/html", 138 "Server": "CherryPy/" + c pg.__version__,139 "Server": "CherryPy/" + cherrypy.__version__, 139 140 "Date": date, 140 141 "Set-Cookie": [], 141 142 "Content-Length": 0 142 143 }) 143 c pg.response.simpleCookie = Cookie.SimpleCookie()144 cherrypy.response.simpleCookie = Cookie.SimpleCookie() 144 145 145 146 self.run() 146 147 147 if c pg.request.method == "HEAD":148 if cherrypy.request.method == "HEAD": 148 149 # HEAD requests MUST NOT return a message-body in the response. 149 c pg.response.body = []150 cherrypy.response.body = [] 150 151 151 152 def run(self): … … 158 159 159 160 applyFilters('beforeRequestBody') 160 if c pg.request.processRequestBody:161 if cherrypy.request.processRequestBody: 161 162 self.processRequestBody() 162 163 163 164 applyFilters('beforeMain') 164 if c pg.response.body is None:165 if cherrypy.response.body is None: 165 166 main() 166 167 167 168 applyFilters('beforeFinalize') 168 169 finalize() 169 except c perror.RequestHandled:170 except cherrypy.RequestHandled: 170 171 pass 171 except c perror.HTTPRedirect, inst:172 except cherrypy.HTTPRedirect, inst: 172 173 # For an HTTPRedirect, we don't go through the regular 173 174 # mechanism: we return the redirect immediately … … 181 182 def processRequestHeaders(self): 182 183 # Parse first line 183 c pg.request.method, path, cpg.request.protocol = self.requestLine.split()184 c pg.request.processRequestBody = cpg.request.method in ("POST",)184 cherrypy.request.method, path, cherrypy.request.protocol = self.requestLine.split() 185 cherrypy.request.processRequestBody = cherrypy.request.method in ("POST",) 185 186 186 187 # find the queryString, or set it to "" if not found 187 188 if "?" in path: 188 c pg.request.path, cpg.request.queryString = path.split("?", 1)189 cherrypy.request.path, cherrypy.request.queryString = path.split("?", 1) 189 190 else: 190 c pg.request.path, cpg.request.queryString = path, ""191 cherrypy.request.path, cherrypy.request.queryString = path, "" 191 192 192 193 # build a paramMap dictionary from queryString 193 pm = cgi.parse_qs(c pg.request.queryString, keep_blank_values=True)194 pm = cgi.parse_qs(cherrypy.request.queryString, keep_blank_values=True) 194 195 for key, val in pm.items(): 195 196 if len(val) == 1: 196 197 pm[key] = val[0] 197 c pg.request.paramMap = pm198 cherrypy.request.paramMap = pm 198 199 199 200 # Process the headers into request.headerMap … … 204 205 # only Konqueror does that), only the last one will remain in headerMap 205 206 # (but they will be correctly stored in request.simpleCookie). 206 c pg.request.headerMap[name] = value207 cherrypy.request.headerMap[name] = value 207 208 208 209 # Handle cookies differently because on Konqueror, multiple cookies 209 210 # come on different lines with the same key 210 211 if name == 'Cookie': 211 c pg.request.simpleCookie.load(value)212 213 msg = "%s - %s" % (c pg.request.remoteAddr, self.requestLine[:-2])214 c pg.log(msg, "HTTP")215 216 c pg.request.base = "http://" + cpg.request.headerMap.get('Host', '')217 c pg.request.browserUrl = cpg.request.base + path212 cherrypy.request.simpleCookie.load(value) 213 214 msg = "%s - %s" % (cherrypy.request.remoteAddr, self.requestLine[:-2]) 215 cherrypy.log(msg, "HTTP") 216 217 cherrypy.request.base = "http://" + cherrypy.request.headerMap.get('Host', '') 218 cherrypy.request.browserUrl = cherrypy.request.base + path 218 219 219 220 # Change objectPath in filters to change 220 221 # the object that will get rendered 221 c pg.request.objectPath = None222 cherrypy.request.objectPath = None 222 223 223 224 # Save original values (in case they get modified by filters) 224 c pg.request.originalPath = cpg.request.path225 c pg.request.originalParamMap = cpg.request.paramMap226 c pg.request.originalParamList = cpg.request.paramList225 cherrypy.request.originalPath = cherrypy.request.path 226 cherrypy.request.originalParamMap = cherrypy.request.paramMap 227 cherrypy.request.originalParamList = cherrypy.request.paramList 227 228 228 229 def processRequestBody(self): … … 230 231 # FieldStorage doesn't work otherwise 231 232 lowerHeaderMap = {} 232 for key, value in c pg.request.headerMap.items():233 for key, value in cherrypy.request.headerMap.items(): 233 234 lowerHeaderMap[key.lower()] = value 234 forms = _cpcgifs.FieldStorage(fp=c pg.request.rfile, headers=lowerHeaderMap,235 forms = _cpcgifs.FieldStorage(fp=cherrypy.request.rfile, headers=lowerHeaderMap, 235 236 environ = {'REQUEST_METHOD': 'POST'}, 236 237 keep_blank_values = 1) … … 239 240 valueList = forms[key] 240 241 if isinstance(valueList, list): 241 c pg.request.paramMap[key] = []242 cherrypy.request.paramMap[key] = [] 242 243 for item in valueList: 243 244 if item.file is not None: … … 245 246 else: 246 247 value = item.value # It's a regular field 247 c pg.request.paramMap[key].append(value)248 cherrypy.request.paramMap[key].append(value) 248 249 else: 249 250 if valueList.file is not None: … … 251 252 else: 252 253 value = valueList.value # It's a regular field 253 c pg.request.paramMap[key] = value254 cherrypy.request.paramMap[key] = value 254 255 255 256 … … 272 273 applyFilters('beforeErrorResponse') 273 274 274 # _cpOnError will probably change c pg.response.body.275 # _cpOnError will probably change cherrypy.response.body. 275 276 # It may also change the headerMap, etc. 276 277 _cputil.getSpecialAttribute('_cpOnError')() … … 283 284 # Bypass them all. 284 285 body = dbltrace % (formatExc(exc), formatExc()) 285 c pg.response.status, cpg.response.headers, body = bareError(body)286 c pg.response.body = body286 cherrypy.response.status, cherrypy.response.headers, body = bareError(body) 287 cherrypy.response.body = body 287 288 288 289 def formatExc(exc=None): … … 317 318 318 319 def main(path=None): 319 """Obtain and set c pg.response.body."""320 """Obtain and set cherrypy.response.body.""" 320 321 if path is None: 321 path = c pg.request.objectPath or cpg.request.path322 path = cherrypy.request.objectPath or cherrypy.request.path 322 323 323 324 while True: … … 326 327 327 328 # Remove "root" from objectPathList and join it to get objectPath 328 c pg.request.objectPath = '/' + '/'.join(objectPathList[1:])329 body = func(*(virtualPathList + c pg.request.paramList),330 **(c pg.request.paramMap))331 c pg.response.body = iterable(body)329 cherrypy.request.objectPath = '/' + '/'.join(objectPathList[1:]) 330 body = func(*(virtualPathList + cherrypy.request.paramList), 331 **(cherrypy.request.paramMap)) 332 cherrypy.response.body = iterable(body) 332 333 return 333 except c perror.InternalRedirect, x:334 except cherrypy.InternalRedirect, x: 334 335 # Try again with the new path 335 336 path = x.path … … 348 349 349 350 def checkStatus(): 350 """Test/set c pg.response.status. Provide Reason-phrase if missing."""351 if not c pg.response.status:352 c pg.response.status = "200 OK"351 """Test/set cherrypy.response.status. Provide Reason-phrase if missing.""" 352 if not cherrypy.response.status: 353 cherrypy.response.status = "200 OK" 353 354 else: 354 status = str(c pg.response.status)355 status = str(cherrypy.response.status) 355 356 parts = status.split(" ", 1) 356 357 if len(parts) == 1: … … 375 376 reason = "" 376 377 377 c pg.response.status = "%s %s" % (code, reason)378 return c pg.response.status378 cherrypy.response.status = "%s %s" % (code, reason) 379 return cherrypy.response.status 379 380 380 381 … … 400 401 401 402 def finalize(): 402 """Transform headerMap + cookies into c pg.response.headers."""403 """Transform headerMap + cookies into cherrypy.response.headers.""" 403 404 404 405 checkStatus() 405 406 406 if (c pg.config.get("server.protocolVersion") != "HTTP/1.1"407 and c pg.response.headerMap.get('Content-Length') == 0):408 content = ''.join(c pg.response.body)409 c pg.response.body = [content]410 c pg.response.headerMap['Content-Length'] = len(content)407 if (cherrypy.config.get("server.protocolVersion") != "HTTP/1.1" 408 and cherrypy.response.headerMap.get('Content-Length') == 0): 409 content = ''.join(cherrypy.response.body) 410 cherrypy.response.body = [content] 411 cherrypy.response.headerMap['Content-Length'] = len(content) 411 412 412 413 # Headers 413 414 headers = [] 414 for key, valueList in c pg.response.headerMap.iteritems():415 for key, valueList in cherrypy.response.headerMap.iteritems(): 415 416 order = _header_order_map.get(key, 3) 416 417 if not isinstance(valueList, list): … … 422 423 # ending with the entity-header fields.' 423 424 headers.sort() 424 c pg.response.headers = [item[1] for item in headers]425 426 cookie = c pg.response.simpleCookie.output()425 cherrypy.response.headers = [item[1] for item in headers] 426 427 cookie = cherrypy.response.simpleCookie.output() 427 428 if cookie: 428 429 name, value = cookie.split(": ", 1) 429 c pg.response.headers.append((name, value))430 return c pg.response.headers430 cherrypy.response.headers.append((name, value)) 431 return cherrypy.response.headers 431 432 432 433 def applyFilters(methodName): … … 466 467 467 468 def serve_file(filename): 468 # If filename is relative, make absolute using c pg.root's module.469 # If filename is relative, make absolute using cherrypy.root's module. 469 470 if not os.path.isabs(filename): 470 root = os.path.dirname(sys.modules[c pg.root.__module__].__file__)471 root = os.path.dirname(sys.modules[cherrypy.root.__module__].__file__) 471 472 filename = os.path.join(root, filename) 472 473 … … 475 476 stat = os.stat(filename) 476 477 except OSError: 477 raise c perror.NotFound(cpg.request.path)478 raise cherrypy.NotFound(cherrypy.request.path) 478 479 479 480 modifTime = stat.st_mtime 480 481 strModifTime = time.strftime("%a, %d %b %Y %H:%M:%S GMT", 481 482 time.gmtime(modifTime)) 482 if c pg.request.headerMap.has_key('If-Modified-Since'):483 if cherrypy.request.headerMap.has_key('If-Modified-Since'): 483 484 # Check if if-modified-since date is the same as strModifTime 484 if c pg.request.headerMap['If-Modified-Since'] == strModifTime:485 c pg.response.status = "304 Not Modified"486 c pg.response.body = []485 if cherrypy.request.headerMap['If-Modified-Since'] == strModifTime: 486 cherrypy.response.status = "304 Not Modified" 487 cherrypy.response.body = [] 487 488 return 488 c pg.response.headerMap['Last-Modified'] = strModifTime489 cherrypy.response.headerMap['Last-Modified'] = strModifTime 489 490 490 491 # Set Content-Length and use an iterable (file object) 491 492 # this way CP won't load the whole file in memory 492 c pg.response.headerMap['Content-Length'] = stat[6]493 c pg.response.body = open(filename, 'rb')493 cherrypy.response.headerMap['Content-Length'] = stat[6] 494 cherrypy.response.body = open(filename, 'rb') 494 495 495 496 # Set content-type based on filename extension … … 500 501 ext = "" 501 502 contentType = mimetypes.types_map.get(ext, "text/plain") 502 c pg.response.headerMap['Content-Type'] = contentType503 cherrypy.response.headerMap['Content-Type'] = contentType 503 504 504 505 … … 509 510 return the object (or None if it doesn't exist). 510 511 """ 511 root = c pg512 root = cherrypy 512 513 for objname in objPathList: 513 514 # maps virtual filenames to Python identifiers (substitutes '.' for '_') 514 515 objname = objname.replace('.', '_') 515 if getattr(c pg, "debug", None):516 if getattr(cherrypy, "debug", None): 516 517 print "Attempting to call method: %s.%s" % (root, objname) 517 518 root = getattr(root, objname, None) … … 542 543 objectPathList = ['root'] + objectPathList + ['index'] 543 544 544 if getattr(c pg, "debug", None):545 if getattr(cherrypy, "debug", None): 545 546 print "Attempting to map path: %s" % tpath 546 547 print " objectPathList: %s" % objectPathList … … 583 584 serve_file(icofile) 584 585 finalize() 585 raise c perror.RequestHandled586 raise cherrypy.RequestHandled 586 587 else: 587 588 # We didn't find anything 588 raise c perror.NotFound(path)589 raise cherrypy.NotFound(path) 589 590 590 591 if isFirst: … … 594 595 if path[-1] != '/': 595 596 newUrl = path + '/' 596 if c pg.request.queryString:597 newUrl += "?" + c pg.request.queryString598 raise c perror.HTTPRedirect(newUrl)597 if cherrypy.request.queryString: 598 newUrl += "?" + cherrypy.request.queryString 599 raise cherrypy.HTTPRedirect(newUrl) 599 600 600 601 return candidate, objectPathList, virtualPathList trunk/cherrypy/_cputil.py
r381 r382 27 27 """ 28 28 29 30 29 """ 31 30 A module containing a few utility classes/functions used by CherryPy 32 31 """ 33 32 34 import time, cpg, cperror 33 import time 34 import cherrypy 35 35 36 36 … … 41 41 42 42 def getObjectTrail(): 43 """ Return all objects from the currenct object to c pg"""44 root = getattr(c pg, 'root', None)43 """ Return all objects from the currenct object to cherrypy """ 44 root = getattr(cherrypy, 'root', None) 45 45 if root: 46 46 objectTrail = [root] 47 47 # Try object path 48 48 try: 49 path = c pg.request.objectPath or cpg.request.path49 path = cherrypy.request.objectPath or cherrypy.request.path 50 50 except AttributeError: 51 51 path = '/' … … 65 65 66 66 def getSpecialAttribute(name): 67 """ Return the special attribute. A special attribute is68 one that applies to all of the children from where it is69 defined, such as_cpFilterList."""67 """Return the special attribute. A special attribute is one that 68 applies to all of the children from where it is defined, such as 69 _cpFilterList.""" 70 70 71 71 # First, we look in the right-most object if this special attribute is implemented. 72 # If not, then we try the previous object and so on until we reach c pg.root72 # If not, then we try the previous object and so on until we reach cherrypy.root 73 73 # If it's still not there, we use the implementation from this module. 74 74 … … 85 85 return globals()[name] 86 86 except KeyError: 87 raise c perror.InternalError("Special attribute %s could not be found"88 % repr(name))87 raise cherrypy.InternalError("Special attribute %s could not be found" 88 % repr(name)) 89 89 90 90 def getSpecialAttributePath(name): … … 92 92 objectList = getObjectTrail() 93 93 if objectList: 94 pathList = (cpg.request.objectPath or cpg.request.path).split("/")[1:] 94 pathList = cherrypy.request.objectPath or cherrypy.request.path 95 pathList = pathList.split("/")[1:] 95 96 for i in xrange(len(objectList) - 1, -1, -1): 96 97 if hasattr(objectList[i], name): 97 98 return "/" + "/".join(pathList[:i] + [name]) 98 raise c perror.InternalError("Special attribute %s could not be found"99 % repr(name))99 raise cherrypy.InternalError("Special attribute %s could not be found" 100 % repr(name)) 100 101 101 102 def _cpLogMessage(msg, context = '', severity = 0): … … 113 114 level = "UNKNOWN" 114 115 try: 115 logToScreen = c pg.config.get('server.logToScreen')116 logToScreen = cherrypy.config.get('server.logToScreen') 116 117 except: 117 118 logToScreen = True … … 119 120 if logToScreen: 120 121 print s 121 if c pg.config.get('server.logFile'):122 f = open(c pg.config.get('server.logFile'), 'ab')122 if cherrypy.config.get('server.logFile'): 123 f = open(cherrypy.config.get('server.logFile'), 'ab') 123 124 f.write(s + '\n') 124 125 f.close() … … 128 129 import sys, traceback 129 130 content = "".join(traceback.format_exception(*sys.exc_info())) 130 c pg.response.body = [content]131 c pg.response.headerMap['Content-Type'] = 'text/plain'132 if c pg.response.headerMap.has_key('Content-Encoding'):133 del c pg.response.headerMap['Content-Encoding']131 cherrypy.response.body = [content] 132 cherrypy.response.headerMap['Content-Type'] = 'text/plain' 133 if cherrypy.response.headerMap.has_key('Content-Encoding'): 134 del cherrypy.response.headerMap['Content-Encoding'] 134 135 135 136 _cpFilterList = [] … … 141 142 virtualhostfilter, xmlrpcfilter, sessionauthenticatefilter 142 143 143 from cherrypy.lib.filter .sessionfilterimport sessionfilter144 from cherrypy.lib.filter import sessionfilter 144 145 145 146 _cachefilter = cachefilter.CacheFilter() … … 236 237 return Builder().build(getObj(s)) 237 238 except: 238 raise c perror.WrongUnreprValue, repr(s)239 raise cherrypy.WrongUnreprValue, repr(s) trunk/cherrypy/_cpwsgi.py
r357 r382  
