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

Changeset 1141

Show
Ignore:
Timestamp:
06/12/06 01:46:25
Author:
fumanchu
Message:

Renamed httptools to "http" to reduce confusion with new cherrypy.tools. Moved non-Tool-related code from cptools to lib/__init__. Added docstrings.

Files:

Legend:

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

    r1139 r1141  
    8080    import datetime 
    8181    now = datetime.datetime.now() 
    82     from cherrypy.lib import httptools 
    83     month = httptools.monthname[now.month][:3].capitalize() 
     82    from cherrypy.lib import http 
     83    month = http.monthname[now.month][:3].capitalize() 
    8484    return '%02d/%s/%04d:%02d:%02d:%02d' % ( 
    8585        now.day, month, now.year, now.hour, now.minute, now.second) 
  • trunk/cherrypy/_cperror.py

    r1139 r1141  
    44from sys import exc_info as _exc_info 
    55from urlparse import urljoin as _urljoin 
    6 from cherrypy.lib import httptools as _httptools 
     6from cherrypy.lib import http as _http 
    77 
    88 
     
    2727            path, pm = path.split("?", 1) 
    2828            request.query_string = pm 
    29             request.params = _httptools.parseQueryString(pm) 
     29            request.params = _http.parseQueryString(pm) 
    3030         
    3131        # Note that urljoin will "do the right thing" whether url is: 
     
    225225     
    226226    try: 
    227         code, reason, message = _httptools.validStatus(status) 
     227        code, reason, message = _http.validStatus(status) 
    228228    except ValueError, x: 
    229229        raise cherrypy.HTTPError(500, x.args[0]) 
  • trunk/cherrypy/_cprequest.py

    r1139 r1141  
    99from cherrypy import _cpcgifs 
    1010from cherrypy._cperror import format_exc, bare_error 
    11 from cherrypy.lib import httptools, profiler 
     11from cherrypy.lib import http, profiler 
    1212 
    1313 
     
    105105        self.header_list = list(headers) 
    106106        self.rfile = rfile 
    107         self.headers = httptools.HeaderMap() 
     107        self.headers = http.HeaderMap() 
    108108        self.simple_cookie = Cookie.SimpleCookie() 
    109109        self.handler = None 
     
    172172                                              100 * 1024 * 1024)) 
    173173                    if mbs > 0: 
    174                         self.rfile = httptools.SizeCheckWrapper(self.rfile, mbs) 
     174                        self.rfile = http.SizeCheckWrapper(self.rfile, mbs) 
    175175                 
    176176                self.hooks.run('before_request_body') 
     
    195195        """Parse the first line (e.g. "GET /path HTTP/1.1") of the request.""" 
    196196        rl = self.request_line 
    197         method, path, qs, proto = httptools.parse_request_line(rl) 
     197        method, path, qs, proto = http.parse_request_line(rl) 
    198198        if path == "*": 
    199199            path = "global" 
     
    221221         
    222222        # cherrypy.request.version == request.protocol in a Version instance. 
    223         self.version = httptools.version_from_http(self.protocol) 
     223        self.version = http.version_from_http(self.protocol) 
    224224         
    225225        # cherrypy.response.version should be used to determine whether or 
    226226        # not to include a given HTTP/1.1 feature in the response content. 
    227227        server_v = cherrypy.config.get('server.protocol_version', 'HTTP/1.0') 
    228         server_v = httptools.version_from_http(server_v) 
     228        server_v = http.version_from_http(server_v) 
    229229        cherrypy.response.version = min(self.version, server_v) 
    230230     
    231231    def process_headers(self): 
    232         self.params = httptools.parseQueryString(self.query_string) 
     232        self.params = http.parseQueryString(self.query_string) 
    233233         
    234234        # Process the headers into self.headers 
     
    330330                                          environ=methenv, 
    331331                                          keep_blank_values=1) 
    332         except httptools.MaxSizeExceeded: 
     332        except http.MaxSizeExceeded: 
    333333            # Post data is too big 
    334334            raise cherrypy.HTTPError(413) 
     
    338338            self.body = forms.file 
    339339        else: 
    340             self.params.update(httptools.paramsFromCGIForm(forms)) 
     340            self.params.update(http.paramsFromCGIForm(forms)) 
    341341     
    342342    def handle_error(self, exc): 
     
    539539        self.body = None 
    540540         
    541         self.headers = httptools.HeaderMap() 
     541        self.headers = http.HeaderMap() 
    542542        content_type = cherrypy.config.get('default_content_type', 'text/html') 
    543543        self.headers.update({ 
    544544            "Content-Type": content_type, 
    545545            "Server": "CherryPy/" + cherrypy.__version__, 
    546             "Date": httptools.HTTPDate(), 
     546            "Date": http.HTTPDate(), 
    547547            "Set-Cookie": [], 
    548548            "Content-Length": None 
     
    559559         
    560560        try: 
    561             code, reason, _ = httptools.validStatus(self.status) 
     561            code, reason, _ = http.validStatus(self.status) 
    562562        except ValueError, x: 
    563563            raise cherrypy.HTTPError(500, x.args[0]) 
  • trunk/cherrypy/_cpserver.py

    r1125 r1141  
    55 
    66import cherrypy 
    7 from cherrypy.lib import cptool
     7from cherrypy.lib import attribute
    88 
    99 
     
    2424            server = _cpwsgi.WSGIServer() 
    2525        if isinstance(server, basestring): 
    26             server = cptools.attributes(server)() 
     26            server = attributes(server)() 
    2727        self.httpserver = server 
    2828         
  • trunk/cherrypy/_cptree.py

    r1121 r1141  
    9393                return path 
    9494         
    95         from cherrypy.lib import httptools 
    96         return httptools.urljoin(script_name, path) 
     95        from cherrypy.lib import http 
     96        return http.urljoin(script_name, path) 
    9797 
  • trunk/cherrypy/_cpwsgi.py

    r1109 r1141  
    55from cherrypy import _cpwsgiserver 
    66from cherrypy._cperror import format_exc, bare_error 
    7 from cherrypy.lib import httptools 
     7from cherrypy.lib import http 
    88 
    99 
     
    139139                                      500 * 1024)) 
    140140        if mhs > 0: 
    141             self.rfile = httptools.SizeCheckWrapper(self.rfile, mhs) 
     141            self.rfile = http.SizeCheckWrapper(self.rfile, mhs) 
    142142     
    143143    def parse_request(self): 
    144144        try: 
    145145            _cpwsgiserver.HTTPRequest.parse_request(self) 
    146         except httptools.MaxSizeExceeded: 
     146        except http.MaxSizeExceeded: 
    147147            msg = "Request Entity Too Large" 
    148148            proto = self.environ.get("SERVER_PROTOCOL", "HTTP/1.0") 
     
    163163                    path = "global" 
    164164                 
    165                 if isinstance(self.rfile, httptools.SizeCheckWrapper): 
     165                if isinstance(self.rfile, http.SizeCheckWrapper): 
    166166                    # Unwrap the rfile 
    167167                    self.rfile = self.rfile.rfile 
  • trunk/cherrypy/config.py

    r1122 r1141  
    55 
    66import cherrypy 
    7 from cherrypy.lib import autoreload, cptools 
     7from cherrypy.lib import autoreload, unrepr 
    88 
    99environments = { 
     
    139139            value = configParser.get(section, option, raw, vars) 
    140140            try: 
    141                 value = cptools.unrepr(value) 
     141                value = unrepr(value) 
    142142            except Exception, x: 
    143143                msg = ("section: %s, option: %s, value: %s" % 
  • trunk/cherrypy/lib/__init__.py

    r762 r1141  
    1 """ 
    2 CherryPy Standard Library 
    3 """ 
     1"""CherryPy Library""" 
    42 
     3import sys as _sys 
     4 
     5 
     6def modules(modulePath): 
     7    """Load a module and retrieve a reference to that module.""" 
     8    try: 
     9        mod = _sys.modules[modulePath] 
     10        if mod is None: 
     11            raise KeyError() 
     12    except KeyError: 
     13        # The last [''] is important. 
     14        mod = __import__(modulePath, globals(), locals(), ['']) 
     15    return mod 
     16 
     17def attributes(fullAttributeName): 
     18    """Load a module and retrieve an attribute of that module.""" 
     19     
     20    # Parse out the path, module, and attribute 
     21    lastDot = fullAttributeName.rfind(u".") 
     22    attrName = fullAttributeName[lastDot + 1:] 
     23    modPath = fullAttributeName[:lastDot] 
     24     
     25    aMod = modules(modPath) 
     26    # Let an AttributeError propagate outward. 
     27    try: 
     28        attr = getattr(aMod, attrName) 
     29    except AttributeError: 
     30        raise AttributeError("'%s' object has no attribute '%s'" 
     31                             % (modPath, attrName)) 
     32     
     33    # Return a reference to the attribute. 
     34    return attr 
     35 
     36 
     37# public domain "unrepr" implementation, found on the web and then improved. 
     38 
     39class _Builder: 
     40     
     41    def build(self, o): 
     42        m = getattr(self, 'build_' + o.__class__.__name__, None) 
     43        if m is None: 
     44            raise TypeError("unrepr does not recognize %s" % 
     45                            repr(o.__class__.__name__)) 
     46        return m(o) 
     47     
     48    def build_CallFunc(self, o): 
     49        callee, args, starargs, kwargs = map(self.build, o.getChildren()) 
     50        return callee(args, *(starargs or ()), **(kwargs or {})) 
     51     
     52    def build_List(self, o): 
     53        return map(self.build, o.getChildren()) 
     54     
     55    def build_Const(self, o): 
     56        return o.value 
     57     
     58    def build_Dict(self, o): 
     59        d = {} 
     60        i = iter(map(self.build, o.getChildren())) 
     61        for el in i: 
     62            d[el] = i.next() 
     63        return d 
     64     
     65    def build_Tuple(self, o): 
     66        return tuple(self.build_List(o)) 
     67     
     68    def build_Name(self, o): 
     69        if o.name == 'None': 
     70            return None 
     71        if o.name == 'True': 
     72            return True 
     73        if o.name == 'False': 
     74            return False 
     75         
     76        # See if the Name is a package or module 
     77        try: 
     78            return modules(o.name) 
     79        except ImportError: 
     80            pass 
     81         
     82        raise TypeError("unrepr could not resolve the name %s" % repr(o.name)) 
     83     
     84    def build_Add(self, o): 
     85        real, imag = map(self.build_Const, o.getChildren()) 
     86        try: 
     87            real = float(real) 
     88        except TypeError: 
     89            raise TypeError("unrepr could not parse real %s" % repr(real)) 
     90        if not isinstance(imag, complex) or imag.real != 0.0: 
     91            raise TypeError("unrepr could not parse imag %s" % repr(imag)) 
     92        return real+imag 
     93     
     94    def build_Getattr(self, o): 
     95        parent = self.build(o.expr) 
     96        return getattr(parent, o.attrname) 
     97     
     98    def build_NoneType(self, o): 
     99        return None 
     100 
     101 
     102def unrepr(s): 
     103    """Return a Python object compiled from a string.""" 
     104    if not s: 
     105        return s 
     106     
     107    import compiler 
     108    p = compiler.parse("a=" + s) 
     109    obj = p.getChildren()[1].getChildren()[0].getChildren()[1] 
     110     
     111    return _Builder().build(obj) 
     112 
  • trunk/cherrypy/lib/cptools.py

    r1134 r1141  
    1 """Tools which CherryPy may invoke.""" 
    2  
    3 import md5 
    4 import sys 
     1"""Functions for builtin CherryPy tools.""" 
    52 
    63import cherrypy 
    7 import httptools 
    8  
    9  
    10 def modules(modulePath): 
    11     """Load a module and retrieve a reference to that module.""" 
    12     try: 
    13         mod = sys.modules[modulePath] 
    14         if mod is None: 
    15             raise KeyError() 
    16     except KeyError: 
    17         # The last [''] is important. 
    18         mod = __import__(modulePath, globals(), locals(), ['']) 
    19     return mod 
    20  
    21 def attributes(fullAttributeName): 
    22     """Load a module and retrieve an attribute of that module.""" 
    23      
    24     # Parse out the path, module, and attribute 
    25     lastDot = fullAttributeName.rfind(u".") 
    26     attrName = fullAttributeName[lastDot + 1:] 
    27     modPath = fullAttributeName[:lastDot] 
    28      
    29     aMod = modules(modPath) 
    30     # Let an AttributeError propagate outward. 
    31     try: 
    32         attr = getattr(aMod, attrName) 
    33     except AttributeError: 
    34         raise AttributeError("'%s' object has no attribute '%s'" 
    35                              % (modPath, attrName)) 
    36      
    37     # Return a reference to the attribute. 
    38     return attr 
    39  
    40  
    41 # public domain "unrepr" implementation, found on the web and then improved. 
    42 import compiler 
    43  
    44 def getObj(s): 
    45     s = "a=" + s 
    46     p = compiler.parse(s) 
    47     return p.getChildren()[1].getChildren()[0].getChildren()[1] 
    48  
    49  
    50 class UnknownType(Exception): 
    51     pass 
    52  
    53  
    54 class Builder: 
    55      
    56     def build(self, o): 
    57         m = getattr(self, 'build_' + o.__class__.__name__, None) 
    58         if m is None: 
    59             raise UnknownType(o.__class__.__name__) 
    60         return m(o) 
    61      
    62     def build_CallFunc(self, o): 
    63         callee, args, starargs, kwargs = map(self.build, o.getChildren()) 
    64         return callee(args, *(starargs or ()), **(kwargs or {})) 
    65      
    66     def build_List(self, o): 
    67         return map(self.build, o.getChildren()) 
    68      
    69     def build_Const(self, o): 
    70         return o.value 
    71      
    72     def build_Dict(self, o): 
    73         d = {} 
    74         i = iter(map(self.build, o.getChildren())) 
    75         for el in i: 
    76             d[el] = i.next() 
    77         return d 
    78      
    79     def build_Tuple(self, o): 
    80         return tuple(self.build_List(o)) 
    81      
    82     def build_Name(self, o): 
    83         if o.name == 'None': 
    84             return None 
    85         if o.name == 'True': 
    86             return True 
    87         if o.name == 'False': 
    88             return False 
    89          
    90         # See if the Name is a package or module 
    91         try: 
    92             return modules(o.name) 
    93         except ImportError: 
    94             pass 
    95          
    96         raise UnknownType(o.name) 
    97      
    98     def build_Add(self, o): 
    99         real, imag = map(self.build_Const, o.getChildren()) 
    100         try: 
    101             real = float(real) 
    102         except TypeError: 
    103             raise UnknownType('Add') 
    104         if not isinstance(imag, complex) or imag.real != 0.0: 
    105             raise UnknownType('Add') 
    106         return real+imag 
    107      
    108     def build_Getattr(self, o): 
    109         parent = self.build(o.expr) 
    110         return getattr(parent, o.attrname) 
    111      
    112     def build_NoneType(self, o): 
    113         return None 
    114  
    115  
    116 def unrepr(s): 
    117     if not s: 
    118         return s 
    119     return Builder().build(getObj(s)) 
     4import http as _http 
    1205 
    1216 
     
    13116     
    13217    if (not etag) and autotags: 
     18        import md5 
    13319        etag = '"%s"' % md5.new(cherrypy.response.collapse_body()).hexdigest() 
    13420        cherrypy.response.headers['ETag'] = etag 
     
    13723        cherrypy.response.ETag = etag 
    13824         
    139         status, reason, msg = httptools.validStatus(cherrypy.response.status) 
     25        status, reason, msg = _http.validStatus(cherrypy.response.status) 
    14026         
    14127        conditions = cherrypy.request.headers.elements('If-Match') or [] 
     
    15844    lastmod = cherrypy.response.headers.get('Last-Modified') 
    15945    if lastmod: 
    160         status, reason, msg = httptools.validStatus(cherrypy.response.status) 
     46        status, reason, msg = _http.validStatus(cherrypy.response.status) 
    16147         
    16248        since = cherrypy.request.headers.get('If-Unmodified-Since') 
     
    221107                 load_user_by_username=None, session_key='username', 
    222108                 on_login=None, on_logout=None, login_screen=None): 
     109    """Assert that the user is logged in.""" 
    223110     
    224111    if login_screen is None: 
     
    311198    cherrypy.request.virtual_prefix = prefix = domains.get(domain, "") 
    312199    if prefix: 
    313         raise cherrypy.InternalRedirect(httptools.urljoin(prefix, cherrypy.request.path_info)) 
     200        raise cherrypy.InternalRedirect(_http.urljoin(prefix, cherrypy.request.path_info)) 
    314201 
    315202def log_traceback(): 
     
    319206 
    320207def log_request_headers(): 
    321     """Write the last error's traceback to the cherrypy error log.""" 
     208    """Write request headers to the cherrypy error log.""" 
    322209    h = ["  %s: %s" % (k, v) for k, v in cherrypy.request.header_list] 
    323210    cherrypy.log('\nRequest Headers:\n' + '\n'.join(h), "HTTP") 
  • trunk/cherrypy/lib/static.py

    r1137 r1141  
    1111 
    1212import cherrypy 
    13 from cherrypy.lib import cptools, httptools 
     13from cherrypy.lib import cptools, http 
    1414 
    1515 
     
    5858    # Set the Last-Modified response header, so that 
    5959    # modified-since validation code can work. 
    60     response.headers['Last-Modified'] = httptools.HTTPDate(time.gmtime(stat.st_mtime)) 
     60    response.headers['Last-Modified'] = http.HTTPDate(time.gmtime(stat.st_mtime)) 
    6161    cptools.validate_since() 
    6262     
     
    7777    if cherrypy.response.version >= (1, 1): 
    7878        response.headers["Accept-Ranges"] = "bytes" 
    79         r = httptools.getRanges(cherrypy.request.headers.get('Range'), c_len) 
     79        r = http.getRanges(cherrypy.request.headers.get('Range'), c_len) 
    8080        if r == []: 
    8181            response.headers['Content-Range'] = "bytes */%s" % c_len 
  • trunk/cherrypy/test/benchmark.py

    r1102 r1141  
    3232 
    3333import cherrypy 
    34 from cherrypy.lib import httptools 
     34from cherrypy.lib import http 
    3535 
    3636 
     
    9292        cherrypy.response.header_list = [("Content-Type", 'text/html'), 
    9393                                         ("Server", "Null CherryPy"), 
    94                                          ("Date", httptools.HTTPDate()), 
     94                                         ("Date", http.HTTPDate()), 
    9595                                         ("Content-Length", "0"), 
    9696                                         ] 
  • trunk/cherrypy/test/helper.py

    r1096 r1141  
    2424 
    2525import cherrypy 
    26 from cherrypy.lib import httptools 
     26from cherrypy.lib import http 
    2727import webtest 
    2828 
     
    4444        """Open the url. Return status, headers, body.""" 
    4545        if self.script_name: 
    46             url = httptools.urljoin(self.script_name, url) 
     46            url = http.urljoin(self.script_name, url) 
    4747        webtest.WebCase.getPage(self, url, headers, method, body, protocol) 
    4848     
  • trunk/cherrypy/test/test_core.py

    r1138 r1141  
    66import cherrypy 
    77from cherrypy import _cptools, tools 
    8 from cherrypy.lib import httptools, static 
     8from cherrypy.lib import http, static 
    99import types 
    1010 
     
    245245        def get_ranges(self): 
    246246            h = cherrypy.request.headers.get('Range') 
    247             return repr(httptools.getRanges(h, 8)) 
     247            return repr(http.getRanges(h, 8)) 
    248248         
    249249        def slice_file(self): 

Hosted by WebFaction

Log in as guest/cpguest to create tickets