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

Changeset 1243

Show
Ignore:
Timestamp:
08/12/06 11:39:31
Author:
fumanchu
Message:

Lots of mixedCase to lower_with_underscores.

Files:

Legend:

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

    r1236 r1243  
    168168    return newfunc 
    169169 
    170 def decorateAll(obj, decorator): 
     170def decorate_all(obj, decorator): 
    171171    """ 
    172172    Recursively decorate all exposed functions of obj and all of its children, 
     
    181181        if callable(value) and getattr(value, "exposed", False): 
    182182            setattr(obj, key, decorate(value, decorator)) 
    183         decorateAll(value, decorator) 
     183        decorate_all(value, decorator) 
    184184 
    185185 
  • trunk/cherrypy/_cpengine.py

    r1231 r1243  
    257257        return cherrypy.response 
    258258 
     259 
     260def drop_privileges(new_user='nobody', new_group='nogroup'): 
     261    """Drop privileges. UNIX only.""" 
     262    # Special thanks to Gavin Baker: http://antonym.org/node/100. 
     263     
     264    import pwd, grp 
     265     
     266    def names(): 
     267        return pwd.getpwuid(os.getuid())[0], grp.getgrgid(os.getgid())[0] 
     268    name, group = names() 
     269    cherrypy.log('Started as %r/%r' % (name, group), "PRIV") 
     270     
     271    if os.getuid() != 0: 
     272        # We're not root so, like, whatever dude. 
     273        cherrypy.log("Already running as %r" % name, "PRIV") 
     274        return 
     275     
     276    # Try setting the new uid/gid (from new_user/new_group). 
     277    try: 
     278        os.setgid(grp.getgrnam(new_group)[2]) 
     279    except OSError, e: 
     280        cherrypy.log('Could not set effective group id: %r' % e, "PRIV") 
     281     
     282    try: 
     283        os.setuid(pwd.getpwnam(new_user)[2]) 
     284    except OSError, e: 
     285        cherrypy.log('Could not set effective user id: %r' % e, "PRIV") 
     286     
     287    # Ensure a very convervative umask 
     288    old_umask = os.umask(077) 
     289    cherrypy.log('Old umask: %o, new umask: 077' % old_umask, "PRIV") 
     290    cherrypy.log('Running as %r/%r' % names(), "PRIV") 
     291 
  • trunk/cherrypy/_cperror.py

    r1231 r1243  
    2727            path, pm = path.split("?", 1) 
    2828            request.query_string = pm 
    29             request.params = _http.parseQueryString(pm) 
     29            request.params = _http.parse_query_string(pm) 
    3030         
    3131        # Note that urljoin will "do the right thing" whether url is: 
     
    246246     
    247247    try: 
    248         code, reason, message = _http.validStatus(status) 
     248        code, reason, message = _http.valid_status(status) 
    249249    except ValueError, x: 
    250250        raise cherrypy.HTTPError(500, x.args[0]) 
  • trunk/cherrypy/_cpmodpy.py

    r1225 r1243  
    9292                               req.protocol, headers, rfile) 
    9393         
    94         sendResponse(req, response.status, response.header_list, response.body) 
     94        send_response(req, response.status, response.header_list, response.body) 
    9595        request.close() 
    9696    except: 
     
    9898        cherrypy.log(tb) 
    9999        s, h, b = bare_error() 
    100         sendResponse(req, s, h, b) 
     100        send_response(req, s, h, b) 
    101101    return apache.OK 
    102102 
    103 def sendResponse(req, status, headers, body): 
     103def send_response(req, status, headers, body): 
    104104    # Set response status 
    105105    req.status = int(status[:3]) 
  • trunk/cherrypy/_cprequest.py

    r1234 r1243  
    250250     
    251251    def process_headers(self): 
    252         self.params = http.parseQueryString(self.query_string) 
     252        self.params = http.parse_query_string(self.query_string) 
    253253         
    254254        # Process the headers into self.headers 
     
    367367            self.body = forms.file 
    368368        else: 
    369             self.params.update(http.paramsFromCGIForm(forms)) 
     369            self.params.update(http.params_from_CGI_form(forms)) 
    370370     
    371371    def handle_error(self, exc): 
     
    545545                    if path[-1:] != '/': 
    546546                        atoms = request.browser_url.split("?", 1) 
    547                         newUrl = atoms.pop(0) + '/' 
     547                        new_url = atoms.pop(0) + '/' 
    548548                        if atoms: 
    549                             newUrl += "?" + atoms[0] 
    550                         raise cherrypy.HTTPRedirect(newUrl) 
     549                            new_url += "?" + atoms[0] 
     550                        raise cherrypy.HTTPRedirect(new_url) 
    551551                return candidate, names[i:-1] 
    552552         
     
    598598 
    599599 
    600 def fileGenerator(input, chunkSize=65536): 
     600def file_generator(input, chunkSize=65536): 
    601601    """Yield the given input (a file object) in chunks (default 64k).""" 
    602602    chunk = input.read(chunkSize) 
     
    622622        # Convert the given value to an iterable object. 
    623623        if isinstance(value, types.FileType): 
    624             value = fileGenerator(value) 
     624            value = file_generator(value) 
    625625        elif isinstance(value, types.GeneratorType): 
    626626            value = flattener(value) 
     
    684684         
    685685        try: 
    686             code, reason, _ = http.validStatus(self.status) 
     686            code, reason, _ = http.valid_status(self.status) 
    687687        except ValueError, x: 
    688688            raise cherrypy.HTTPError(500, x.args[0]) 
  • trunk/cherrypy/config.py

    r1236 r1243  
    225225    cherrypy.log("Server parameters:", 'CONFIG') 
    226226     
    227     serverVars = [ 
     227    server_vars = [ 
    228228                  'environment', 
    229229                  'log_to_screen', 
     
    238238                 ] 
    239239     
    240     for var in serverVars: 
     240    for var in server_vars: 
    241241        cherrypy.log("  %s: %s" % (var, get(var)), 'CONFIG') 
    242242 
  • trunk/cherrypy/lib/__init__.py

    r1141 r1243  
    1515    return mod 
    1616 
    17 def attributes(fullAttributeName): 
     17def attributes(full_attribute_name): 
    1818    """Load a module and retrieve an attribute of that module.""" 
    1919     
    2020    # Parse out the path, module, and attribute 
    21     lastDot = fullAttributeName.rfind(u".") 
    22     attrName = fullAttributeName[lastDot + 1:] 
    23     modPath = fullAttributeName[:lastDot] 
     21    last_dot = full_attribute_name.rfind(u".") 
     22    attr_name = full_attribute_name[last_dot + 1:] 
     23    mod_path = full_attribute_name[:last_dot] 
    2424     
    25     aMod = modules(modPath) 
     25    mod = modules(mod_path) 
    2626    # Let an AttributeError propagate outward. 
    2727    try: 
    28         attr = getattr(aMod, attrName) 
     28        attr = getattr(mod, attr_name) 
    2929    except AttributeError: 
    3030        raise AttributeError("'%s' object has no attribute '%s'" 
    31                              % (modPath, attrName)) 
     31                             % (mod_path, attr_name)) 
    3232     
    3333    # Return a reference to the attribute. 
  • trunk/cherrypy/lib/caching.py

    r1224 r1243  
    1111    def __init__(self): 
    1212        self.clear() 
    13         t = threading.Thread(target=self.expireCache, name='expireCache') 
    14         self.expirationThread = t 
     13        t = threading.Thread(target=self.expire_cache, name='expire_cache') 
     14        self.expiration_thread = t 
    1515        t.setDaemon(True) 
    1616        t.start() 
     
    2020        self.cache = {} 
    2121        self.expirations = {} 
    22         self.totPuts = 0 
    23         self.totGets = 0 
    24         self.totHits = 0 
    25         self.totExpires = 0 
    26         self.totNonModified = 0 
     22        self.tot_puts = 0 
     23        self.tot_gets = 0 
     24        self.tot_hist = 0 
     25        self.tot_expires = 0 
     26        self.tot_non_modified = 0 
    2727        self.cursize = 0 
    2828     
     
    3131    key = property(_key) 
    3232     
    33     def expireCache(self): 
    34         # expireCache runs in a separate thread which the servers are 
     33    def expire_cache(self): 
     34        # expire_cache runs in a separate thread which the servers are 
    3535        # not aware of. It's possible that "time" will be set to None 
    3636        # arbitrarily, so we check "while time" to avoid exceptions. 
     
    3838        while time: 
    3939            now = time.time() 
    40             for expirationTime, objects in self.expirations.items(): 
    41                 if expirationTime <= now: 
    42                     for objSize, objKey in objects: 
     40            for expiration_time, objects in self.expirations.items(): 
     41                if expiration_time <= now: 
     42                    for obj_size, obj_key in objects: 
    4343                        try: 
    44                             del self.cache[objKey] 
    45                             self.totExpires += 1 
    46                             self.cursize -= objSize 
     44                            del self.cache[obj_key] 
     45                            self.tot_expires += 1 
     46                            self.cursize -= obj_size 
    4747                        except KeyError: 
    4848                            # the key may have been deleted elsewhere 
    4949                            pass 
    50                     del self.expirations[expirationTime] 
     50                    del self.expirations[expiration_time] 
    5151            time.sleep(0.1) 
    5252     
    5353    def get(self): 
    5454        """Return the object if in the cache, else None.""" 
    55         self.totGets += 1 
    56         cacheItem = self.cache.get(self.key, None) 
    57         if cacheItem: 
    58             self.totHits += 1 
    59             return cacheItem 
     55        self.tot_gets += 1 
     56        cache_item = self.cache.get(self.key, None) 
     57        if cache_item: 
     58            self.tot_hist += 1 
     59            return cache_item 
    6060        else: 
    6161            return None 
     
    6666        if len(self.cache) < conf("tools.caching.maxobjects", 1000): 
    6767            # Size check no longer includes header length 
    68             objSize = len(obj[2]) 
    69             maxobjsize = conf("tools.caching.maxobjsize", 100000) 
     68            obj_size = len(obj[2]) 
     69            maxobj_size = conf("tools.caching.maxobj_size", 100000) 
    7070             
    71             totalSize = self.cursize + objSize 
     71            total_size = self.cursize + obj_size 
    7272            maxsize = conf("tools.caching.maxsize", 10000000) 
    7373             
    7474            # checks if there's space for the object 
    75             if (objSize < maxobjsize and totalSize < maxsize): 
     75            if (obj_size < maxobj_size and total_size < maxsize): 
    7676                # add to the expirations list and cache 
    77                 expirationTime = time.time() + conf("tools.caching.delay", 600) 
    78                 objKey = self.key 
    79                 bucket = self.expirations.setdefault(expirationTime, []) 
    80                 bucket.append((objSize, objKey)) 
    81                 self.cache[objKey] = obj 
    82                 self.totPuts += 1 
    83                 self.cursize = totalSize 
     77                expiration_time = time.time() + conf("tools.caching.delay", 600) 
     78                obj_key = self.key 
     79                bucket = self.expirations.setdefault(expiration_time, []) 
     80                bucket.append((obj_size, obj_key)) 
     81                self.cache[obj_key] = obj 
     82                self.tot_puts += 1 
     83                self.cursize = total_size 
    8484 
    8585 
     
    9797        cherrypy.request.cached = c = False 
    9898    else: 
    99         cacheData = cherrypy._cache.get() 
    100         cherrypy.request.cached = c = bool(cacheData) 
     99        cache_data = cherrypy._cache.get() 
     100        cherrypy.request.cached = c = bool(cache_data) 
    101101     
    102102    if c: 
    103103        response = cherrypy.response 
    104         s, response.headers, b, create_time = cacheData 
     104        s, response.headers, b, create_time = cache_data 
    105105         
    106106        # Add the required Age header 
     
    111111        except cherrypy.HTTPError, x: 
    112112            if x.status == 304: 
    113                 cherrypy._cache.totNonModified += 1 
     113                cherrypy._cache.tot_non_modified += 1 
    114114            raise 
    115115         
  • trunk/cherrypy/lib/cptools.py

    r1233 r1243  
    2323        cherrypy.response.ETag = etag 
    2424         
    25         status, reason, msg = _http.validStatus(cherrypy.response.status) 
     25        status, reason, msg = _http.valid_status(cherrypy.response.status) 
    2626         
    2727        conditions = cherrypy.request.headers.elements('If-Match') or [] 
     
    4444    lastmod = cherrypy.response.headers.get('Last-Modified') 
    4545    if lastmod: 
    46         status, reason, msg = _http.validStatus(cherrypy.response.status) 
     46        status, reason, msg = _http.valid_status(cherrypy.response.status) 
    4747         
    4848        since = cherrypy.request.headers.get('If-Unmodified-Since') 
  • trunk/cherrypy/lib/encoding.py

    r1233 r1243  
    3333 
    3434def decode_params(encoding): 
    35     decodedParams = {} 
     35    decoded_params = {} 
    3636    for key, value in cherrypy.request.params.items(): 
    3737        if hasattr(value, 'file'): 
    3838            # This is a file being uploaded: skip it 
    39             decodedParams[key] = value 
     39            decoded_params[key] = value 
    4040        elif isinstance(value, list): 
    4141            # value is a list: decode each element 
    42             decodedParams[key] = [v.decode(encoding) for v in value] 
     42            decoded_params[key] = [v.decode(encoding) for v in value] 
    4343        else: 
    4444            # value is a regular string: decode it 
    45             decodedParams[key] = value.decode(encoding) 
     45            decoded_params[key] = value.decode(encoding) 
    4646     
    4747    # Decode all or nothing, so we can try again on error. 
    48     cherrypy.request.params = decodedParams 
     48    cherrypy.request.params = decoded_params 
    4949 
    5050 
  • trunk/cherrypy/lib/http.py

    r1225 r1243  
    88 
    99from BaseHTTPServer import BaseHTTPRequestHandler 
    10 responseCodes = BaseHTTPRequestHandler.responses.copy() 
     10response_codes = BaseHTTPRequestHandler.responses.copy() 
    1111 
    1212# From http://www.cherrypy.org/ticket/361 
    13 responseCodes[500] = ('Internal error', 
     13response_codes[500] = ('Internal error', 
    1414                      'The server encountered an unexpected condition ' 
    1515                      'which prevented it from fulfilling the request.') 
    16 responseCodes[503] = ('Service Unavailable', 
     16response_codes[503] = ('Service Unavailable', 
    1717                      'The server is currently unable to handle the ' 
    1818                      'request due to a temporary overloading or ' 
     
    3838    return int(protocol_str[5]), int(protocol_str[7]) 
    3939 
    40 def getRanges(headervalue, content_length): 
     40def get_ranges(headervalue, content_length): 
    4141    """Return a list of (start, stop) indices from a Range header, or None. 
    4242     
     
    194194    return decodedvalue 
    195195 
    196 def validStatus(status): 
     196def valid_status(status): 
    197197    """Return legal HTTP status Code, Reason-phrase and Message. 
    198198     
     
    226226                         "(%s is out of range)." % repr(code)) 
    227227     
    228     if code not in responseCodes: 
     228    if code not in response_codes: 
    229229        # code is unknown but not illegal 
    230         defaultReason, message = "", "" 
     230        default_reason, message = "", "" 
    231231    else: 
    232         defaultReason, message = responseCodes[code] 
     232        default_reason, message = response_codes[code] 
    233233     
    234234    if reason is None: 
    235         reason = defaultReason 
     235        reason = default_reason 
    236236     
    237237    return code, reason, message 
     
    240240image_map_pattern = re.compile(r"[0-9]+,[0-9]+") 
    241241 
    242 def parseQueryString(query_string, keep_blank_values=True): 
    243     """Build a paramMap dictionary from a query_string.""" 
     242def parse_query_string(query_string, keep_blank_values=True): 
     243    """Build a params dictionary from a query_string.""" 
    244244    if image_map_pattern.match(query_string): 
    245245        # Server-side image map. Map the coords to 'x' and 'y' 
     
    254254    return pm 
    255255 
    256 def paramsFromCGIForm(form): 
    257     paramMap = {} 
     256def params_from_CGI_form(form): 
     257    params = {} 
    258258    for key in form.keys(): 
    259         valueList = form[key] 
    260         if isinstance(valueList, list): 
    261             paramMap[key] = [] 
    262             for item in valueList: 
     259        value_list = form[key] 
     260        if isinstance(value_list, list): 
     261            params[key] = [] 
     262            for item in value_list: 
    263263                if item.filename is not None: 
    264264                    value = item # It's a file upload 
    265265                else: 
    266266                    value = item.value # It's a regular field 
    267                 paramMap[key].append(value) 
     267                params[key].append(value) 
    268268        else: 
    269             if valueList.filename is not None: 
    270                 value = valueList # It's a file upload 
     269            if value_list.filename is not None: 
     270                value = value_list # It's a file upload 
    271271            else: 
    272                 value = valueList.value # It's a regular field 
    273             paramMap[key] = value 
    274     return paramMap 
     272                value = value_list.value # It's a regular field 
     273            params[key] = value 
     274    return params 
    275275 
    276276 
  • trunk/cherrypy/lib/static.py

    r1242 r1243  
    7575    if cherrypy.request.protocol >= (1, 1): 
    7676        response.headers["Accept-Ranges"] = "bytes" 
    77         r = http.getRanges(cherrypy.request.headers.get('Range'), c_len) 
     77        r = http.get_ranges(cherrypy.request.headers.get('Range'), c_len) 
    7878        if r == []: 
    7979            response.headers['Content-Range'] = "bytes */%s" % c_len 
     
    9999##                del response.headers['Content-Length'] 
    100100                 
    101                 def fileRanges(): 
     101                def file_ranges(): 
    102102                    for start, stop in r: 
    103103                        yield "--" + boundary 
     
    110110                    # Final boundary 
    111111                    yield "--" + boundary 
    112                 response.body = fileRanges() 
     112                response.body = file_ranges() 
    113113        else: 
    114114            response.headers['Content-Length'] = c_len 
  • trunk/cherrypy/lib/tidy.py

    r1190 r1243  
    1717    # the tidy tool, by its very nature it's not generator friendly,  
    1818    # so we just collapse the body and work with it. 
    19     originalBody = cherrypy.response.collapse_body() 
     19    orig_body = cherrypy.response.collapse_body() 
    2020     
    2121    fct = cherrypy.response.headers.get('Content-Type', '') 
     
    2727     
    2828    if ct == 'text/html': 
    29         pageFile = os.path.join(temp_dir, 'page.html') 
    30         open(pageFile, 'wb').write(originalBody) 
     29        page_file = os.path.join(temp_dir, 'page.html') 
     30        open(page_file, 'wb').write(orig_body) 
    3131         
    32         outFile = os.path.join(temp_dir, 'tidy.out') 
    33         errFile = os.path.join(temp_dir, 'tidy.err') 
    34         tidyEncoding = encoding.replace('-', '') 
    35         if tidyEncoding
    36             tidyEncoding = '-' + tidyEncoding 
     32        out_file = os.path.join(temp_dir, 'tidy.out') 
     33        err_file = os.path.join(temp_dir, 'tidy.err') 
     34        tidy_enc = encoding.replace('-', '') 
     35        if tidy_enc
     36            tidy_enc = '-' + tidy_enc 
    3737         
    3838        strict_xml = (" -xml", "")[bool(strict_xml)] 
    3939        os.system('"%s" %s%s -f %s -o %s %s' % 
    40                   (tidy_path, tidyEncoding, strict_xml, 
    41                    errFile, outFile, pageFile)) 
    42         errs = open(errFile, 'rb').read() 
     40                  (tidy_path, tidy_enc, strict_xml, 
     41                   err_file, out_file, page_file)) 
     42        errs = open(err_file, 'rb').read() 
    4343         
    4444        new_errs = [] 
     
    4646            if (err.find('Warning') != -1 or err.find('Error') != -1): 
    4747                ignore = 0 
    48                 for errIgn in errors_to_ignore or []: 
    49                     if err.find(errIgn) != -1: 
     48                for err_ign in errors_to_ignore or []: 
     49                    if err.find(err_ign) != -1: 
    5050                        ignore = 1 
    5151                        break 
     
    5555        if new_errs: 
    5656            cherrypy.response.body = wrong_content('<br />'.join(new_errs), 
    57                                                    original_body) 
     57                                                   orig_body) 
    5858        elif strict_xml: 
    5959            # The HTML is OK, but is it valid XML? 
    6060            # Use elementtree to parse XML 
    6161            from elementtree.ElementTree import parse 
    62             tagList = ['nbsp', 'quot'] 
    63             for tag in tagList: 
    64                 originalBody = originalBody.replace('&' + tag + ';', tag.upper()) 
     62            tag_list = ['nbsp', 'quot'] 
     63            for tag in tag_list: 
     64                orig_body = orig_body.replace('&' + tag + ';', tag.upper()) 
    6565             
    6666            if encoding: 
    6767                enctag = '<?xml version="1.0" encoding="%s"?>' % encoding 
    68                 originalBody = enctag + originalBody 
     68                orig_body = enctag + orig_body 
    6969             
    70             f = StringIO.StringIO(originalBody) 
     70            f = StringIO.StringIO(orig_body) 
    7171            try: 
    7272                tree = parse(f) 
    7373            except: 
    7474                # Wrong XML 
    75                 bodyFile = StringIO.StringIO() 
    76                 traceback.print_exc(file = bodyFile) 
    77                 bodyFile = '<br />'.join(bodyFile.getvalue()) 
    78                 cherrypy.response.body = wrong_content(bodyFile, originalbody, "XML") 
     75                body_file = StringIO.StringIO() 
     76                traceback.print_exc(file = body_file) 
     77                body_file = '<br />'.join(body_file.getvalue()) 
     78                cherrypy.response.body = wrong_content(body_file, orig_body, "XML") 
    7979 
    8080def html_space(text): 
     
    9696    # the tidy tool, by its very nature it's not generator friendly,  
    9797    # so we just collect the body and work with it. 
    98     original_body = cherrypy.response.collapse_body() 
     98    orig_body = cherrypy.response.collapse_body() 
    9999     
    100100    fct = cherrypy.response.headers.get('Content-Type', '') 
     
    109109        #   Javascript code nsgmls complains about it) 
    110110        while True: 
    111             i = original_body.find('<script') 
     111            i = orig_body.find('<script') 
    112112            if i == -1: 
    113113                break 
    114             j = original_body.find('</script>', i) 
     114            j = orig_body.find('</script>', i) 
    115115            if j == -1: 
    116116                break 
    117             original_body = original_body[:i] + original_body[j+9:] 
     117            orig_body = orig_body[:i] + orig_body[j+9:] 
    118118 
    119119        page_file = os.path.join(temp_dir, 'page.html') 
    120         open(page_file, 'wb').write(original_body) 
     120        open(page_file, 'wb').write(orig_body) 
    121121         
    122122        err_file = os.path.join(temp_dir, 'nsgmls.err') 
     
    139139        if new_errs: 
    140140            cherrypy.response.body = wrong_content('<br />'.join(new_errs), 
    141                                                    original_body) 
     141                                                   orig_body) 
    142142 
  • trunk/cherrypy/test/test_core.py

    r1225 r1243  
    243243        def get_ranges(self): 
    244244            h = cherrypy.request.headers.get('Range') 
    245             return repr(http.getRanges(h, 8)) 
     245            return repr(http.get_ranges(h, 8)) 
    246246         
    247247        def slice_file(self): 

Hosted by WebFaction

Log in as guest/cpguest to create tickets