Commits

Robert Brewer committed c7eea74

Tweaks to docs, line lengths, tests, and number of serving lookups.

Comments (0)

Files changed (9)

-Copyright (c) 2004-2005, CherryPy Team (team@cherrypy.org)
+Copyright (c) 2004-2006, CherryPy Team (team@cherrypy.org)
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without modification, 
         # expose is being called directly, before the method has been bound
         return expose_(func)
     else:
-        # expose is being called as a decorator
         if alias is None:
-            alias = func
-        return expose_
+            # expose is being called as a decorator "@expose"
+            func.exposed = True
+            return func
+        else:
+            # expose is returning a decorator "@expose(alias=...)"
+            return expose_
 
 
 # Set up config last so it can wrap other top-level objects

cherrypy/_cpconfig.py

             setattr(cherrypy.engine, atoms[1], v)
         elif namespace == "log":
             setattr(cherrypy.log, atoms[1], v)
-    
-    def wrap(**kwargs):
-        """Decorator to set _cp_config on a handler using the given kwargs."""
-        def wrapper(f):
-            if not hasattr(f, "_cp_config"):
-                f._cp_config = {}
-            f._cp_config.update(kwargs)
-            return f
-        return wrapper
-    wrap = staticmethod(wrap)
 
 
 class _Parser(ConfigParser.ConfigParser):

cherrypy/_cprequest.py

         request = cherrypy.request
         resource, vpath = self.find_handler(path_info)
         
-        # Decode any leftover %2F in the virtual_path atoms.
-        vpath = [x.replace("%2F", "/") for x in vpath]
-        
         if resource:
             # Set Allow header
             avail = [m for m in dir(resource) if m.isupper()]
             cherrypy.response.headers['Allow'] = ", ".join(avail)
             
             # Find the subhandler
-            meth = cherrypy.request.method.upper()
+            meth = request.method.upper()
             func = getattr(resource, meth, None)
             if func is None and meth == "HEAD":
                 func = getattr(resource, "GET", None)
             if func:
+                # Decode any leftover %2F in the virtual_path atoms.
+                vpath = [x.replace("%2F", "/") for x in vpath]
                 request.handler = LateParamPageHandler(func, *vpath)
             else:
                 request.handler = cherrypy.HTTPError(405)

cherrypy/lib/caching.py

         self.cursize = 0
     
     def _key(self):
-        return cherrypy.request.config.get("tools.caching.key", cherrypy.request.browser_url)
+        return cherrypy.request.config.get("tools.caching.key",
+                                           cherrypy.request.browser_url)
     key = property(_key)
     
     def expire_cache(self):
     cherrypy._cache = cache_class()
 
 def get():
+    request = cherrypy.request
     # Ignore POST, PUT, DELETE.
     # See http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.10.
-    invalid = cherrypy.request.config.get("tools.caching.invalid_methods",
-                                          ("POST", "PUT", "DELETE"))
-    if cherrypy.request.method in invalid:
-        cherrypy.request.cached = c = False
+    invalid = request.config.get("tools.caching.invalid_methods",
+                                 ("POST", "PUT", "DELETE"))
+    if request.method in invalid:
+        request.cached = c = False
     else:
         cache_data = cherrypy._cache.get()
-        cherrypy.request.cached = c = bool(cache_data)
+        request.cached = c = bool(cache_data)
     
     if c:
         response = cherrypy.response
     none of the above response headers are set.
     """
     
+    response = cherrypy.response
+    
     cacheable = False
     if not force:
         # some header names that indicate that the response can be cached
         for indicator in ('Etag', 'Last-Modified', 'Age', 'Expires'):
-            if indicator in cherrypy.response.headers:
+            if indicator in response.headers:
                 cacheable = True
                 break
     
             secs = (86400 * secs.days) + secs.seconds
         
         if secs == 0:
-            if force or "Pragma" not in cherrypy.response.headers:
-                cherrypy.response.headers["Pragma"] = "no-cache"
+            if force or "Pragma" not in response.headers:
+                response.headers["Pragma"] = "no-cache"
             if cherrypy.request.protocol >= (1, 1):
-                if force or "Cache-Control" not in cherrypy.response.headers:
-                    cherrypy.response.headers["Cache-Control"] = "no-cache"
+                if force or "Cache-Control" not in response.headers:
+                    response.headers["Cache-Control"] = "no-cache"
         
-        expiry = http.HTTPDate(cherrypy.response.time + secs)
-        if force or "Expires" not in cherrypy.response.headers:
-            cherrypy.response.headers["Expires"] = expiry
+        expiry = http.HTTPDate(response.time + secs)
+        if force or "Expires" not in response.headers:
+            response.headers["Expires"] = expiry

cherrypy/lib/cptools.py

     automatic, and if no other code has provided an ETag value, then no
     checks will be performed against If-Match or If-None-Match headers.
     """
+    response = cherrypy.response
+    
     # Guard against being run twice.
-    if hasattr(cherrypy.response, "ETag"):
+    if hasattr(response, "ETag"):
         return
     
-    etag = cherrypy.response.headers.get('ETag')
+    etag = response.headers.get('ETag')
     
     if (not etag) and autotags:
         import md5
-        etag = '"%s"' % md5.new(cherrypy.response.collapse_body()).hexdigest()
-        cherrypy.response.headers['ETag'] = etag
+        etag = '"%s"' % md5.new(response.collapse_body()).hexdigest()
+        response.headers['ETag'] = etag
     
     if etag:
-        cherrypy.response.ETag = etag
+        response.ETag = etag
         
-        status, reason, msg = _http.valid_status(cherrypy.response.status)
+        status, reason, msg = _http.valid_status(response.status)
         
-        conditions = cherrypy.request.headers.elements('If-Match') or []
+        request = cherrypy.request
+        
+        conditions = request.headers.elements('If-Match') or []
         conditions = [str(x) for x in conditions]
         if conditions and not (conditions == ["*"] or etag in conditions):
             if status >= 200 and status < 299:
                 raise cherrypy.HTTPError(412)
         
-        conditions = cherrypy.request.headers.elements('If-None-Match') or []
+        conditions = request.headers.elements('If-None-Match') or []
         conditions = [str(x) for x in conditions]
         if conditions == ["*"] or etag in conditions:
             if status >= 200 and status < 299:
-                if cherrypy.request.method in ("GET", "HEAD"):
+                if request.method in ("GET", "HEAD"):
                     raise cherrypy.HTTPRedirect([], 304)
                 else:
                     raise cherrypy.HTTPError(412)
     If no code has set the Last-Modified response header, then no validation
     will be performed.
     """
-    lastmod = cherrypy.response.headers.get('Last-Modified')
+    response = cherrypy.response
+    lastmod = response.headers.get('Last-Modified')
     if lastmod:
-        status, reason, msg = _http.valid_status(cherrypy.response.status)
+        status, reason, msg = _http.valid_status(response.status)
         
-        since = cherrypy.request.headers.get('If-Unmodified-Since')
+        request = cherrypy.request
+        
+        since = request.headers.get('If-Unmodified-Since')
         if since and since != lastmod:
             if (status >= 200 and status < 299) or status == 412:
                 raise cherrypy.HTTPError(412)
         
-        since = cherrypy.request.headers.get('If-Modified-Since')
+        since = request.headers.get('If-Modified-Since')
         if since and since == lastmod:
             if (status >= 200 and status < 299) or status == 304:
-                if cherrypy.request.method in ("GET", "HEAD"):
+                if request.method in ("GET", "HEAD"):
                     raise cherrypy.HTTPRedirect([], 304)
                 else:
                     raise cherrypy.HTTPError(412)
     but also to have  http://www.mydom1.com/mydom2/  etc to be valid pages in
     their own right.
     """
-    if hasattr(cherrypy.request, "virtual_prefix"):
+    request = cherrypy.request
+    
+    if hasattr(request, "virtual_prefix"):
         return
     
-    domain = cherrypy.request.headers.get('Host', '')
+    domain = request.headers.get('Host', '')
     if use_x_forwarded_host:
-        domain = cherrypy.request.headers.get("X-Forwarded-Host", domain)
+        domain = request.headers.get("X-Forwarded-Host", domain)
     
-    cherrypy.request.virtual_prefix = prefix = domains.get(domain, "")
+    request.virtual_prefix = prefix = domains.get(domain, "")
     if prefix:
-        raise cherrypy.InternalRedirect(_http.urljoin(prefix, cherrypy.request.path_info))
+        raise cherrypy.InternalRedirect(_http.urljoin(prefix, request.path_info))
 
 def log_traceback():
     """Write the last error's traceback to the cherrypy error log."""

cherrypy/lib/wsgiapp.py

     for hosting WSGI apps in non-WSGI environments (yikes!)
     """
     
+    request = cherrypy.request
+    
     # create and populate the wsgi environ
     environ = dict()
     environ["wsgi.version"] = (1,0)
-    environ["wsgi.url_scheme"] = cherrypy.request.scheme
-    environ["wsgi.input"] = cherrypy.request.rfile
+    environ["wsgi.url_scheme"] = request.scheme
+    environ["wsgi.input"] = request.rfile
     environ["wsgi.errors"] = sys.stderr
     environ["wsgi.multithread"] = True
     environ["wsgi.multiprocess"] = False
     environ["wsgi.run_once"] = False
-    environ["REQUEST_METHOD"] = cherrypy.request.method
-    environ["SCRIPT_NAME"] = cherrypy.request.script_name
-    environ["PATH_INFO"] = cherrypy.request.path_info
-    environ["QUERY_STRING"] = cherrypy.request.query_string
-    environ["SERVER_PROTOCOL"] = cherrypy.request.protocol
-    environ["SERVER_NAME"] = cherrypy.request.local.name
-    environ["SERVER_PORT"] = cherrypy.request.local.port
-    environ["REMOTE_HOST"] = cherrypy.request.remote.name
-    environ["REMOTE_ADDR"] = cherrypy.request.remote.ip
-    environ["REMOTE_PORT"] = cherrypy.request.remote.port
+    environ["REQUEST_METHOD"] = request.method
+    environ["SCRIPT_NAME"] = request.script_name
+    environ["PATH_INFO"] = request.path_info
+    environ["QUERY_STRING"] = request.query_string
+    environ["SERVER_PROTOCOL"] = request.protocol
+    environ["SERVER_NAME"] = request.local.name
+    environ["SERVER_PORT"] = request.local.port
+    environ["REMOTE_HOST"] = request.remote.name
+    environ["REMOTE_ADDR"] = request.remote.ip
+    environ["REMOTE_PORT"] = request.remote.port
     # then all the http headers
-    headers = cherrypy.request.headers
+    headers = request.headers
     environ["CONTENT_TYPE"] = headers.get("Content-type", "")
     environ["CONTENT_LENGTH"] = headers.get("Content-length", "")
     for (k, v) in headers.iteritems():

cherrypy/test/test_config.py

         _cp_config = {'foo': 'this',
                       'bar': 'that'}
         
+        # @cherrypy.expose(alias=('global_', 'xyz'))
         def index(self, key):
             return cherrypy.request.config.get(key, "None")
-        index.exposed = True
-        global_ = index
-        xyz = index
+        index = cherrypy.expose(index, alias=('global_', 'xyz'))
     
     class Foo:
         

cherrypy/test/test_conn.py

 
 import httplib
 import socket
+import sys
 import time
 
 import cherrypy
             conn._output("Host: %s" % self.HOST)
             conn._send_output()
             response = conn.response_class(conn.sock, method="GET")
-            self.assertRaises(socket.error, response.begin)
+            try:
+                response.begin()
+            except:
+                if not isinstance(sys.exc_info()[1],
+                                  (socket.error, httplib.BadStatusLine)):
+                    self.fail("Writing to timed out socket didn't fail"
+                              " as it should have: %s" % sys.exc_info()[1])
+            else:
+                self.fail("Writing to timed out socket didn't fail"
+                          " as it should have.")
             
             conn.close()