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

Changeset 382

Show
Ignore:
Timestamp:
06/25/05 15:37:39
Author:
fumanchu
Message:

Implements ticket #195.
1. cpg module removed, all content moved into cherrypy.init.
2. Removed some circular imports in sessionfilter by moving sessionfilter.sessionfilter and _sessionTypes into sessionfilter.init.
3. renamed _cpconfig to "config".
4. renamed _cpserver to "server".
5. renamed cperror to _cperror; cherrypy.init now imports * from _cperror.

Files:

Legend:

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

    r310 r382  
     1""" 
     2Copyright (c) 2004, CherryPy Team (team@cherrypy.org) 
     3All rights reserved. 
     4 
     5Redistribution and use in source and binary forms, with or without modification,  
     6are 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 
     17THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND  
     18ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED  
     19WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE  
     20DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE  
     21FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL  
     22DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR  
     23SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER  
     24CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,  
     25OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE  
     26OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
     27""" 
     28 
     29""" 
     30Global module that all modules developing with CherryPy should import. 
     31""" 
     32 
    133__version__ = '2.1.0 alpha' 
     34 
     35from _cperror import * 
     36 
     37import config 
     38import server 
     39 
     40_httpserver = None 
     41 
     42# decorator function for exposing methods 
     43def expose(func): 
     44    func.exposed = True 
     45    return func 
     46 
     47def 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  
    4040 
    4141class WrongResponseType(Error): 
    42     """ Happens when the cpg.response.body is not a string """ 
     42    """ Happens when the cherrypy.response.body is not a string """ 
    4343    pass 
    4444 
     
    6565     
    6666    def __init__(self, path, queryString=None): 
    67         from cherrypy import cpg 
     67        import cherrypy 
    6868        import cgi 
    6969         
    7070        self.path = path 
    7171        if queryString is not None: 
    72             cpg.request.queryString = queryString 
     72            cherrypy.request.queryString = queryString 
    7373             
    74             pm = cgi.parse_qs(cpg.request.queryString, keep_blank_values=True) 
     74            pm = cgi.parse_qs(cherrypy.request.queryString, keep_blank_values=True) 
    7575            for key, val in pm.items(): 
    7676                if len(val) == 1: 
    7777                    pm[key] = val[0] 
    78             cpg.request.paramMap = pm 
     78            cherrypy.request.paramMap = pm 
    7979         
    80         cpg.request.browserUrl = cpg.request.base + path 
     80        cherrypy.request.browserUrl = cherrypy.request.base + path 
    8181 
    8282 
     
    9191    def __init__(self, urls, status=None): 
    9292        import urlparse 
    93         from cherrypy import cpg 
     93        import cherrypy 
    9494         
    9595        if isinstance(urls, basestring): 
     
    9999        for url in urls: 
    100100            if url.startswith("/"): 
    101                 url = urlparse.urljoin(cpg.request.base, url) 
     101                url = urlparse.urljoin(cherrypy.request.base, url) 
    102102            abs_urls.append(url) 
    103103        self.urls = abs_urls 
     
    107107        # http://ppewww.ph.gla.ac.uk/~flavell/www/post-redirect.html 
    108108        if status is None: 
    109             if cpg.request.protocol == "HTTP/1.1": 
     109            if cherrypy.request.protocol == "HTTP/1.1": 
    110110                status = 303 
    111111            else: 
     
    119119     
    120120    def set_response(self): 
    121         import cpg 
    122         cpg.response.status = status = self.status 
    123         cpg.response.headerMap['Content-Type'] = "text/html" 
     121        import cherrypy 
     122        cherrypy.response.status = status = self.status 
     123        cherrypy.response.headerMap['Content-Type'] = "text/html" 
    124124         
    125125        if status in (300, 301, 302, 303, 307): 
    126126            # "The ... URI SHOULD be given by the Location field 
    127127            # in the response." 
    128             cpg.response.headerMap['Location'] = self.urls[0] 
     128            cherrypy.response.headerMap['Location'] = self.urls[0] 
    129129             
    130130            # "Unless the request method was HEAD, the entity of the response 
     
    137137                   307: "This resource has moved temporarily to <a href='%s'>%s</a>.", 
    138138                   }[status] 
    139             cpg.response.body = "<br />\n".join([msg % (url, url) 
     139            cherrypy.response.body = "<br />\n".join([msg % (url, url) 
    140140                                                 for url in self.urls]) 
    141141        elif status == 304: 
     
    146146             
    147147            # "The 304 response MUST NOT contain a message-body." 
    148             cpg.response.body = [] 
     148            cherrypy.response.body = [] 
    149149        elif status == 305: 
    150150            # Use Proxy. 
    151151            # self.urls[0] should be the URI of the proxy. 
    152             cpg.response.headerMap['Location'] = self.urls[0] 
    153             cpg.response.body = [] 
     152            cherrypy.response.headerMap['Location'] = self.urls[0] 
     153            cherrypy.response.body = [] 
    154154        else: 
    155155            raise ValueError("The %s status code is unknown." % status) 
  • trunk/cherrypy/_cphttpserver.py

    r357 r382  
    2828 
    2929import threading, SocketServer, BaseHTTPServer, socket, Queue 
    30 import cpg, _cpserver, _cphttptools 
     30import cherrypy 
     31from cherrypy import _cphttptools 
    3132 
    3233try: 
     
    4950    def address_string(self): 
    5051        """ Try to do a reverse DNS based on [server]reverseDNS in the config file """ 
    51         if cpg.config.get('server.reverseDNS'): 
     52        if cherrypy.config.get('server.reverseDNS'): 
    5253            return BaseHTTPServer.BaseHTTPRequestHandler.address_string(self) 
    5354        else: 
     
    8081            return 
    8182         
    82         cpg.request.multithread = cpg.config.get("server.threadPool") > 1 
    83         cpg.request.multiprocess = False 
    84         _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) 
    8990        wfile = self.wfile 
    90         wfile.write("%s %s\r\n" % (self.protocol_version, cpg.response.status)) 
    91          
    92         for name, value in cpg.response.headers: 
     91        wfile.write("%s %s\r\n" % (self.protocol_version, cherrypy.response.status)) 
     92         
     93        for name, value in cherrypy.response.headers: 
    9394            wfile.write("%s: %s\r\n" % (name, value)) 
    9495         
    9596        wfile.write("\r\n") 
    9697        try: 
    97             for chunk in cpg.response.body: 
     98            for chunk in cherrypy.response.body: 
    9899                wfile.write(chunk) 
    99100        except: 
     
    107108    def log_message(self, format, *args): 
    108109        """ We have to override this to use our own logging mechanism """ 
    109         cpg.log(format % args, "HTTP") 
     110        cherrypy.log(format % args, "HTTP") 
    110111 
    111112 
     
    141142            return 1 
    142143        except (KeyboardInterrupt, SystemExit): 
    143             cpg.log("<Ctrl-C> hit: shutting down http server", "HTTP") 
     144            cherrypy.log("<Ctrl-C> hit: shutting down http server", "HTTP") 
    144145            self.shutdown() 
    145146     
     
    195196        """Handle an error gracefully.  May be overridden.""" 
    196197        errorBody = _cphttptools.formatExc() 
    197         cpg.log(errorBody) 
     198        cherrypy.log(errorBody) 
    198199 
    199200 
     
    273274            request, client_address = self.get_request() 
    274275        except (KeyboardInterrupt, SystemExit): 
    275             cpg.log("<Ctrl-C> hit: shutting down", "HTTP") 
     276            cherrypy.log("<Ctrl-C> hit: shutting down", "HTTP") 
    276277            return 0 
    277278        except socket.error, e: 
     
    296297     
    297298    # Set protocol_version 
    298     proto = cpg.config.get('server.protocolVersion') 
     299    proto = cherrypy.config.get('server.protocolVersion') 
    299300    if not proto: 
    300301        proto = "HTTP/1.0" 
     
    302303     
    303304    # Select the appropriate server based on config options 
    304     sockFile = cpg.config.get('server.socketFile') 
    305     threadPool = cpg.config.get('server.threadPool') 
     305    sockFile = cherrypy.config.get('server.socketFile') 
     306    threadPool = cherrypy.config.get('server.threadPool') 
    306307    if sockFile: 
    307308        # AF_UNIX socket 
     
    320321        else: 
    321322            ServerClass = CherryHTTPServer 
    322         server_address = (cpg.config.get('server.socketHost'), 
    323                           cpg.config.get('server.socketPort')) 
    324      
    325     ServerClass.request_queue_size = cpg.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') 
    326327     
    327328    if handler is None: 
  • trunk/cherrypy/_cphttptools.py

    r376 r382  
    3535from lib.filter import basefilter 
    3636 
    37 import cpg, _cputil, cperror, _cpcgifs 
     37import cherrypy 
     38from cherrypy import _cputil, _cpcgifs 
    3839 
    3940# Can't use cStringIO; doesn't support unicode strings   
     
    106107     
    107108    def __init__(self, clientAddress, remoteHost, requestLine, headers, rfile): 
    108         # When __init__ is finished, cpg.response should have three attributes: 
     109        # When __init__ is finished, cherrypy.response should have three attributes: 
    109110        #   status, e.g. "200 OK" 
    110111        #   headers, a list of (name, value) tuples 
     
    116117        self.requestHeaders = headers 
    117118         
    118         # Prepare cpg.request variables 
    119         cpg.request.remoteAddr = clientAddress 
    120         cpg.request.remoteHost = remoteHost 
    121         cpg.request.paramList = [] # Only used for Xml-Rpc 
    122         cpg.request.headerMap = {} 
    123         cpg.request.requestLine = requestLine 
    124         cpg.request.simpleCookie = Cookie.SimpleCookie() 
    125         cpg.request.rfile = rfile 
    126          
    127         # Prepare cpg.response variables 
    128         cpg.response.status = None 
    129         cpg.response.headers = None 
    130         cpg.response.body = None 
     119        # 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 
    131132         
    132133        year, month, day, hh, mm, ss, wd, y, z = time.gmtime() 
    133134        date = ("%s, %02d %3s %4d %02d:%02d:%02d GMT" % 
    134135                (weekdayname[wd], day, monthname[month], year, hh, mm, ss)) 
    135         cpg.response.headerMap = KeyTitlingDict() 
    136         cpg.response.headerMap.update({ 
     136        cherrypy.response.headerMap = KeyTitlingDict() 
     137        cherrypy.response.headerMap.update({ 
    137138            "Content-Type": "text/html", 
    138             "Server": "CherryPy/" + cpg.__version__, 
     139            "Server": "CherryPy/" + cherrypy.__version__, 
    139140            "Date": date, 
    140141            "Set-Cookie": [], 
    141142            "Content-Length": 0 
    142143        }) 
    143         cpg.response.simpleCookie = Cookie.SimpleCookie() 
     144        cherrypy.response.simpleCookie = Cookie.SimpleCookie() 
    144145         
    145146        self.run() 
    146147         
    147         if cpg.request.method == "HEAD": 
     148        if cherrypy.request.method == "HEAD": 
    148149            # HEAD requests MUST NOT return a message-body in the response. 
    149             cpg.response.body = [] 
     150            cherrypy.response.body = [] 
    150151     
    151152    def run(self): 
     
    158159                     
    159160                    applyFilters('beforeRequestBody') 
    160                     if cpg.request.processRequestBody: 
     161                    if cherrypy.request.processRequestBody: 
    161162                        self.processRequestBody() 
    162163                     
    163164                    applyFilters('beforeMain') 
    164                     if cpg.response.body is None: 
     165                    if cherrypy.response.body is None: 
    165166                        main() 
    166167                     
    167168                    applyFilters('beforeFinalize') 
    168169                    finalize() 
    169                 except cperror.RequestHandled: 
     170                except cherrypy.RequestHandled: 
    170171                    pass 
    171                 except cperror.HTTPRedirect, inst: 
     172                except cherrypy.HTTPRedirect, inst: 
    172173                    # For an HTTPRedirect, we don't go through the regular 
    173174                    # mechanism: we return the redirect immediately 
     
    181182    def processRequestHeaders(self): 
    182183        # Parse first line 
    183         cpg.request.method, path, cpg.request.protocol = self.requestLine.split() 
    184         cpg.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",) 
    185186         
    186187        # find the queryString, or set it to "" if not found 
    187188        if "?" in path: 
    188             cpg.request.path, cpg.request.queryString = path.split("?", 1) 
     189            cherrypy.request.path, cherrypy.request.queryString = path.split("?", 1) 
    189190        else: 
    190             cpg.request.path, cpg.request.queryString = path, "" 
     191            cherrypy.request.path, cherrypy.request.queryString = path, "" 
    191192         
    192193        # build a paramMap dictionary from queryString 
    193         pm = cgi.parse_qs(cpg.request.queryString, keep_blank_values=True) 
     194        pm = cgi.parse_qs(cherrypy.request.queryString, keep_blank_values=True) 
    194195        for key, val in pm.items(): 
    195196            if len(val) == 1: 
    196197                pm[key] = val[0] 
    197         cpg.request.paramMap = pm 
     198        cherrypy.request.paramMap = pm 
    198199         
    199200        # Process the headers into request.headerMap 
     
    204205            # only Konqueror does that), only the last one will remain in headerMap 
    205206            # (but they will be correctly stored in request.simpleCookie). 
    206             cpg.request.headerMap[name] = value 
     207            cherrypy.request.headerMap[name] = value 
    207208             
    208209            # Handle cookies differently because on Konqueror, multiple cookies 
    209210            # come on different lines with the same key 
    210211            if name == 'Cookie': 
    211                 cpg.request.simpleCookie.load(value) 
    212          
    213         msg = "%s - %s" % (cpg.request.remoteAddr, self.requestLine[:-2]) 
    214         cpg.log(msg, "HTTP") 
    215          
    216         cpg.request.base = "http://" + cpg.request.headerMap.get('Host', '') 
    217         cpg.request.browserUrl = cpg.request.base + path 
     212                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 
    218219         
    219220        # Change objectPath in filters to change 
    220221        # the object that will get rendered 
    221         cpg.request.objectPath = None 
     222        cherrypy.request.objectPath = None 
    222223         
    223224        # Save original values (in case they get modified by filters) 
    224         cpg.request.originalPath = cpg.request.path 
    225         cpg.request.originalParamMap = cpg.request.paramMap 
    226         cpg.request.originalParamList = cpg.request.paramList 
     225        cherrypy.request.originalPath = cherrypy.request.path 
     226        cherrypy.request.originalParamMap = cherrypy.request.paramMap 
     227        cherrypy.request.originalParamList = cherrypy.request.paramList 
    227228     
    228229    def processRequestBody(self): 
     
    230231        # FieldStorage doesn't work otherwise 
    231232        lowerHeaderMap = {} 
    232         for key, value in cpg.request.headerMap.items(): 
     233        for key, value in cherrypy.request.headerMap.items(): 
    233234            lowerHeaderMap[key.lower()] = value 
    234         forms = _cpcgifs.FieldStorage(fp=cpg.request.rfile, headers=lowerHeaderMap, 
     235        forms = _cpcgifs.FieldStorage(fp=cherrypy.request.rfile, headers=lowerHeaderMap, 
    235236                                      environ = {'REQUEST_METHOD': 'POST'}, 
    236237                                      keep_blank_values = 1) 
     
    239240            valueList = forms[key] 
    240241            if isinstance(valueList, list): 
    241                 cpg.request.paramMap[key] = [] 
     242                cherrypy.request.paramMap[key] = [] 
    242243                for item in valueList: 
    243244                    if item.file is not None: 
     
    245246                    else: 
    246247                        value = item.value # It's a regular field 
    247                     cpg.request.paramMap[key].append(value) 
     248                    cherrypy.request.paramMap[key].append(value) 
    248249            else: 
    249250                if valueList.file is not None: 
     
    251252                else: 
    252253                    value = valueList.value # It's a regular field 
    253                 cpg.request.paramMap[key] = value 
     254                cherrypy.request.paramMap[key] = value 
    254255 
    255256 
     
    272273        applyFilters('beforeErrorResponse') 
    273274         
    274         # _cpOnError will probably change cpg.response.body. 
     275        # _cpOnError will probably change cherrypy.response.body. 
    275276        # It may also change the headerMap, etc. 
    276277        _cputil.getSpecialAttribute('_cpOnError')() 
     
    283284        # Bypass them all. 
    284285        body = dbltrace % (formatExc(exc), formatExc()) 
    285         cpg.response.status, cpg.response.headers, body = bareError(body) 
    286         cpg.response.body = body 
     286        cherrypy.response.status, cherrypy.response.headers, body = bareError(body) 
     287        cherrypy.response.body = body 
    287288 
    288289def formatExc(exc=None): 
     
    317318 
    318319def main(path=None): 
    319     """Obtain and set cpg.response.body.""" 
     320    """Obtain and set cherrypy.response.body.""" 
    320321    if path is None: 
    321         path = cpg.request.objectPath or cpg.request.path 
     322        path = cherrypy.request.objectPath or cherrypy.request.path 
    322323     
    323324    while True: 
     
    326327             
    327328            # Remove "root" from objectPathList and join it to get objectPath 
    328             cpg.request.objectPath = '/' + '/'.join(objectPathList[1:]) 
    329             body = func(*(virtualPathList + cpg.request.paramList), 
    330                         **(cpg.request.paramMap)) 
    331             cpg.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) 
    332333            return 
    333         except cperror.InternalRedirect, x: 
     334        except cherrypy.InternalRedirect, x: 
    334335            # Try again with the new path 
    335336            path = x.path 
     
    348349 
    349350def checkStatus(): 
    350     """Test/set cpg.response.status. Provide Reason-phrase if missing.""" 
    351     if not cpg.response.status: 
    352         cpg.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" 
    353354    else: 
    354         status = str(cpg.response.status) 
     355        status = str(cherrypy.response.status) 
    355356        parts = status.split(" ", 1) 
    356357        if len(parts) == 1: 
     
    375376                reason = "" 
    376377         
    377         cpg.response.status = "%s %s" % (code, reason) 
    378     return cpg.response.status 
     378        cherrypy.response.status = "%s %s" % (code, reason) 
     379    return cherrypy.response.status 
    379380 
    380381 
     
    400401 
    401402def finalize(): 
    402     """Transform headerMap + cookies into cpg.response.headers.""" 
     403    """Transform headerMap + cookies into cherrypy.response.headers.""" 
    403404     
    404405    checkStatus() 
    405406     
    406     if (cpg.config.get("server.protocolVersion") != "HTTP/1.1" 
    407         and cpg.response.headerMap.get('Content-Length') == 0): 
    408         content = ''.join(cpg.response.body) 
    409         cpg.response.body = [content] 
    410         cpg.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) 
    411412     
    412413    # Headers 
    413414    headers = [] 
    414     for key, valueList in cpg.response.headerMap.iteritems(): 
     415    for key, valueList in cherrypy.response.headerMap.iteritems(): 
    415416        order = _header_order_map.get(key, 3) 
    416417        if not isinstance(valueList, list): 
     
    422423    # ending with the entity-header fields.' 
    423424    headers.sort() 
    424     cpg.response.headers = [item[1] for item in headers] 
    425      
    426     cookie = cpg.response.simpleCookie.output() 
     425    cherrypy.response.headers = [item[1] for item in headers] 
     426     
     427    cookie = cherrypy.response.simpleCookie.output() 
    427428    if cookie: 
    428429        name, value = cookie.split(": ", 1) 
    429         cpg.response.headers.append((name, value)) 
    430     return cpg.response.headers 
     430        cherrypy.response.headers.append((name, value)) 
     431    return cherrypy.response.headers 
    431432 
    432433def applyFilters(methodName): 
     
    466467 
    467468def serve_file(filename): 
    468     # If filename is relative, make absolute using cpg.root's module. 
     469    # If filename is relative, make absolute using cherrypy.root's module. 
    469470    if not os.path.isabs(filename): 
    470         root = os.path.dirname(sys.modules[cpg.root.__module__].__file__) 
     471        root = os.path.dirname(sys.modules[cherrypy.root.__module__].__file__) 
    471472        filename = os.path.join(root, filename) 
    472473     
     
    475476        stat = os.stat(filename) 
    476477    except OSError: 
    477         raise cperror.NotFound(cpg.request.path) 
     478        raise cherrypy.NotFound(cherrypy.request.path) 
    478479     
    479480    modifTime = stat.st_mtime 
    480481    strModifTime = time.strftime("%a, %d %b %Y %H:%M:%S GMT", 
    481482                                 time.gmtime(modifTime)) 
    482     if cpg.request.headerMap.has_key('If-Modified-Since'): 
     483    if cherrypy.request.headerMap.has_key('If-Modified-Since'): 
    483484        # Check if if-modified-since date is the same as strModifTime 
    484         if cpg.request.headerMap['If-Modified-Since'] == strModifTime: 
    485             cpg.response.status = "304 Not Modified" 
    486             cpg.response.body = [] 
     485        if cherrypy.request.headerMap['If-Modified-Since'] == strModifTime: 
     486            cherrypy.response.status = "304 Not Modified" 
     487            cherrypy.response.body = [] 
    487488            return 
    488     cpg.response.headerMap['Last-Modified'] = strModifTime 
     489    cherrypy.response.headerMap['Last-Modified'] = strModifTime 
    489490     
    490491    # Set Content-Length and use an iterable (file object) 
    491492    #   this way CP won't load the whole file in memory 
    492     cpg.response.headerMap['Content-Length'] = stat[6] 
    493     cpg.response.body = open(filename, 'rb') 
     493    cherrypy.response.headerMap['Content-Length'] = stat[6] 
     494    cherrypy.response.body = open(filename, 'rb') 
    494495     
    495496    # Set content-type based on filename extension 
     
    500501        ext = "" 
    501502    contentType = mimetypes.types_map.get(ext, "text/plain") 
    502     cpg.response.headerMap['Content-Type'] = contentType 
     503    cherrypy.response.headerMap['Content-Type'] = contentType 
    503504 
    504505 
     
    509510         return the object (or None if it doesn't exist). 
    510511    """ 
    511     root = cpg 
     512    root = cherrypy 
    512513    for objname in objPathList: 
    513514        # maps virtual filenames to Python identifiers (substitutes '.' for '_') 
    514515        objname = objname.replace('.', '_') 
    515         if getattr(cpg, "debug", None): 
     516        if getattr(cherrypy, "debug", None): 
    516517            print "Attempting to call method: %s.%s" % (root, objname) 
    517518        root = getattr(root, objname, None) 
     
    542543    objectPathList = ['root'] + objectPathList + ['index'] 
    543544     
    544     if getattr(cpg, "debug", None): 
     545    if getattr(cherrypy, "debug", None): 
    545546        print "Attempting to map path: %s" % tpath 
    546547        print "    objectPathList: %s" % objectPathList 
     
    583584            serve_file(icofile) 
    584585            finalize() 
    585             raise cperror.RequestHandled 
     586            raise cherrypy.RequestHandled 
    586587        else: 
    587588            # We didn't find anything 
    588             raise cperror.NotFound(path) 
     589            raise cherrypy.NotFound(path) 
    589590     
    590591    if isFirst: 
     
    594595        if path[-1] != '/': 
    595596            newUrl = path + '/' 
    596             if cpg.request.queryString: 
    597                 newUrl += "?" + cpg.request.queryString 
    598             raise cperror.HTTPRedirect(newUrl) 
     597            if cherrypy.request.queryString: 
     598                newUrl += "?" + cherrypy.request.queryString 
     599            raise cherrypy.HTTPRedirect(newUrl) 
    599600     
    600601    return candidate, objectPathList, virtualPathList 
  • trunk/cherrypy/_cputil.py

    r381 r382  
    2727""" 
    2828 
    29  
    3029""" 
    3130A module containing a few utility classes/functions used by CherryPy 
    3231""" 
    3332 
    34 import time, cpg, cperror 
     33import time 
     34import cherrypy 
    3535 
    3636 
     
    4141 
    4242def getObjectTrail(): 
    43     """ Return all objects from the currenct object to cpg """ 
    44     root = getattr(cpg, 'root', None) 
     43    """ Return all objects from the currenct object to cherrypy """ 
     44    root = getattr(cherrypy, 'root', None) 
    4545    if root: 
    4646        objectTrail = [root] 
    4747        # Try object path 
    4848        try: 
    49             path = cpg.request.objectPath or cpg.request.path 
     49            path = cherrypy.request.objectPath or cherrypy.request.path 
    5050        except AttributeError: 
    5151            path = '/' 
     
    6565 
    6666def getSpecialAttribute(name): 
    67     """ Return the special attribute. A special attribute is 
    68     one that applies to all of the children from where it i
    69     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 a
     69    _cpFilterList.""" 
    7070     
    7171    # 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 cpg.root 
     72    # If not, then we try the previous object and so on until we reach cherrypy.root 
    7373    # If it's still not there, we use the implementation from this module. 
    7474     
     
    8585        return globals()[name] 
    8686    except KeyError: 
    87         raise cperror.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)) 
    8989 
    9090def getSpecialAttributePath(name): 
     
    9292    objectList = getObjectTrail() 
    9393    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:] 
    9596        for i in xrange(len(objectList) - 1, -1, -1): 
    9697            if hasattr(objectList[i], name): 
    9798                return "/" + "/".join(pathList[:i] + [name]) 
    98     raise cperror.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)) 
    100101 
    101102def _cpLogMessage(msg, context = '', severity = 0): 
     
    113114        level = "UNKNOWN" 
    114115    try: 
    115         logToScreen = cpg.config.get('server.logToScreen') 
     116        logToScreen = cherrypy.config.get('server.logToScreen') 
    116117    except: 
    117118        logToScreen = True 
     
    119120    if logToScreen: 
    120121        print s 
    121     if cpg.config.get('server.logFile'): 
    122         f = open(cpg.config.get('server.logFile'), 'ab') 
     122    if cherrypy.config.get('server.logFile'): 
     123        f = open(cherrypy.config.get('server.logFile'), 'ab') 
    123124        f.write(s + '\n') 
    124125        f.close() 
     
    128129    import sys, traceback 
    129130    content = "".join(traceback.format_exception(*sys.exc_info())) 
    130     cpg.response.body = [content] 
    131     cpg.response.headerMap['Content-Type'] = 'text/plain' 
    132     if cpg.response.headerMap.has_key('Content-Encoding'): 
    133         del cpg.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'] 
    134135 
    135136_cpFilterList = [] 
     
    141142    virtualhostfilter, xmlrpcfilter, sessionauthenticatefilter 
    142143 
    143 from cherrypy.lib.filter.sessionfilter import sessionfilter 
     144from cherrypy.lib.filter import sessionfilter 
    144145 
    145146_cachefilter = cachefilter.CacheFilter() 
     
    236237        return Builder().build(getObj(s)) 
    237238    except: 
    238         raise cperror.WrongUnreprValue, repr(s) 
     239        raise cherrypy.WrongUnreprValue, repr(s) 
  • trunk/cherrypy/_cpwsgi.py

    r357 r382