Commits

Jason R. Coombs committed ac23a50

Resaved with excess whitespace trimmed.

Comments (0)

Files changed (1)

cherrypy/_cperror.py

 
 class InternalRedirect(CherryPyException):
     """Exception raised to switch to the handler for a different URL.
-    
+
     This exception will redirect processing to another path within the site
     (without informing the client). Provide the new path as an argument when
     raising the exception. Provide any params in the querystring for the new URL.
     """
-    
+
     def __init__(self, path, query_string=""):
         import cherrypy
         self.request = cherrypy.serving.request
-        
+
         self.query_string = query_string
         if "?" in path:
             # Separate any params included in the path
             path, self.query_string = path.split("?", 1)
-        
+
         # Note that urljoin will "do the right thing" whether url is:
         #  1. a URL relative to root (e.g. "/dummy")
         #  2. a URL relative to the current path
         # Note that any query string will be discarded.
         path = _urljoin(self.request.path_info, path)
-        
+
         # Set a 'path' member attribute so that code which traps this
         # error can have access to it.
         self.path = path
-        
+
         CherryPyException.__init__(self, path, self.query_string)
 
 
 class HTTPRedirect(CherryPyException):
     """Exception raised when the request should be redirected.
-    
+
     This exception will force a HTTP redirect to the URL or URL's you give it.
     The new URL must be passed as the first argument to the Exception,
     e.g., HTTPRedirect(newUrl). Multiple URLs are allowed in a list.
 
     If one of the provided URL is a unicode object, it will be encoded
     using the default encoding or the one passed in parameter.
-    
+
     There are multiple types of redirect, from which you can select via the
     ``status`` argument. If you do not provide a ``status`` arg, it defaults to
     303 (or 302 if responding with HTTP/1.0).
-    
+
     Examples::
-    
+
         raise cherrypy.HTTPRedirect("")
         raise cherrypy.HTTPRedirect("/abs/path", 307)
         raise cherrypy.HTTPRedirect(["path1", "path2?a=1&b=2"], 301)
-    
+
     See :ref:`redirectingpost` for additional caveats.
     """
-    
+
     status = None
     """The integer HTTP status code to emit."""
-    
+
     urls = None
     """The list of URL's to emit."""
 
     encoding = 'utf-8'
     """The encoding when passed urls are not native strings"""
-    
+
     def __init__(self, urls, status=None, encoding=None):
         import cherrypy
         request = cherrypy.serving.request
-        
+
         if isinstance(urls, basestring):
             urls = [urls]
-        
+
         abs_urls = []
         for url in urls:
             url = tonative(url, encoding or self.encoding)
-                
+
             # Note that urljoin will "do the right thing" whether url is:
             #  1. a complete URL with host (e.g. "http://www.example.com/test")
             #  2. a URL relative to root (e.g. "/dummy")
             url = _urljoin(cherrypy.url(), url)
             abs_urls.append(url)
         self.urls = abs_urls
-        
+
         # RFC 2616 indicates a 301 response code fits our goal; however,
         # browser support for 301 is quite messy. Do 302/303 instead. See
         # http://www.alanflavell.org.uk/www/post-redirect.html
             status = int(status)
             if status < 300 or status > 399:
                 raise ValueError("status must be between 300 and 399.")
-        
+
         self.status = status
         CherryPyException.__init__(self, abs_urls, status)
-    
+
     def set_response(self):
         """Modify cherrypy.response status, headers, and body to represent self.
-        
+
         CherryPy uses this internally, but you can also use it to create an
         HTTPRedirect object and set its output without *raising* the exception.
         """
         import cherrypy
         response = cherrypy.serving.response
         response.status = status = self.status
-        
+
         if status in (300, 301, 302, 303, 307):
             response.headers['Content-Type'] = "text/html;charset=utf-8"
             # "The ... URI SHOULD be given by the Location field
             # in the response."
             response.headers['Location'] = self.urls[0]
-            
+
             # "Unless the request method was HEAD, the entity of the response
             # SHOULD contain a short hypertext note with a hyperlink to the
             # new URI(s)."
             # "The response MUST include the following header fields:
             # Date, unless its omission is required by section 14.18.1"
             # The "Date" header should have been set in Response.__init__
-            
+
             # "...the response SHOULD NOT include other entity-headers."
             for key in ('Allow', 'Content-Encoding', 'Content-Language',
                         'Content-Length', 'Content-Location', 'Content-MD5',
                         'Last-Modified'):
                 if key in response.headers:
                     del response.headers[key]
-            
+
             # "The 304 response MUST NOT contain a message-body."
             response.body = None
             # Previous code may have set C-L, so we have to reset it.
             response.headers.pop('Content-Length', None)
         else:
             raise ValueError("The %s status code is unknown." % status)
-    
+
     def __call__(self):
         """Use this exception as a request.handler (raise self)."""
         raise self
 def clean_headers(status):
     """Remove any headers which should not apply to an error response."""
     import cherrypy
-    
+
     response = cherrypy.serving.response
-    
+
     # Remove headers which applied to the original content,
     # but do not apply to the error page.
     respheaders = response.headers
                 "Content-Location", "Content-MD5", "Last-Modified"]:
         if key in respheaders:
             del respheaders[key]
-    
+
     if status != 416:
         # A server sending a response with status code 416 (Requested
         # range not satisfiable) SHOULD include a Content-Range field
 
 class HTTPError(CherryPyException):
     """Exception used to return an HTTP error code (4xx-5xx) to the client.
-    
+
     This exception can be used to automatically send a response using a http status
     code, with an appropriate error page. It takes an optional
     ``status`` argument (which must be between 400 and 599); it defaults to 500
     which will be returned in the response body. See
     `RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4>`_
     for a complete list of available error codes and when to use them.
-    
+
     Examples::
-        
+
         raise cherrypy.HTTPError(403)
         raise cherrypy.HTTPError("403 Forbidden", "You are not allowed to access this resource.")
     """
-    
+
     status = None
     """The HTTP status code. May be of type int or str (with a Reason-Phrase)."""
-    
+
     code = None
     """The integer HTTP status code."""
-    
+
     reason = None
     """The HTTP Reason-Phrase string."""
-    
+
     def __init__(self, status=500, message=None):
         self.status = status
         try:
             self.code, self.reason, defaultmsg = _httputil.valid_status(status)
         except ValueError:
             raise self.__class__(500, _exc_info()[1].args[0])
-        
+
         if self.code < 400 or self.code > 599:
             raise ValueError("status must be between 400 and 599.")
-        
+
         # See http://www.python.org/dev/peps/pep-0352/
         # self.message = message
         self._message = message or defaultmsg
         CherryPyException.__init__(self, status, message)
-    
+
     def set_response(self):
         """Modify cherrypy.response status, headers, and body to represent self.
-        
+
         CherryPy uses this internally, but you can also use it to create an
         HTTPError object and set its output without *raising* the exception.
         """
         import cherrypy
-        
+
         response = cherrypy.serving.response
-        
+
         clean_headers(self.code)
-        
+
         # In all cases, finalize will be called after this method,
         # so don't bother cleaning up response values here.
         response.status = self.status
             tb = format_exc()
         response.headers['Content-Type'] = "text/html;charset=utf-8"
         response.headers.pop('Content-Length', None)
-        
+
         content = ntob(self.get_error_page(self.status, traceback=tb,
                                            message=self._message), 'utf-8')
         response.body = content
-        
+
         _be_ie_unfriendly(self.code)
-    
+
     def get_error_page(self, *args, **kwargs):
         return get_error_page(*args, **kwargs)
-    
+
     def __call__(self):
         """Use this exception as a request.handler (raise self)."""
         raise self
 
 class NotFound(HTTPError):
     """Exception raised when a URL could not be mapped to any handler (404).
-    
+
     This is equivalent to raising
     :class:`HTTPError("404 Not Found") <cherrypy._cperror.HTTPError>`.
     """
-    
+
     def __init__(self, path=None):
         if path is None:
             import cherrypy
 
 def get_error_page(status, **kwargs):
     """Return an HTML page, containing a pretty error response.
-    
+
     status should be an int or a str.
     kwargs will be interpolated into the page template.
     """
     import cherrypy
-    
+
     try:
         code, reason, message = _httputil.valid_status(status)
     except ValueError:
         raise cherrypy.HTTPError(500, _exc_info()[1].args[0])
-    
+
     # We can't use setdefault here, because some
     # callers send None for kwarg values.
     if kwargs.get('status') is None:
         kwargs['traceback'] = ''
     if kwargs.get('version') is None:
         kwargs['version'] = cherrypy.__version__
-    
+
     for k, v in iteritems(kwargs):
         if v is None:
             kwargs[k] = ""
         else:
             kwargs[k] = _escape(kwargs[k])
-    
+
     # Use a custom template or callable for the error page?
     pages = cherrypy.serving.request.error_page
     error_page = pages.get(code) or pages.get('default')
                 m += "<br />"
             m += "In addition, the custom error page failed:\n<br />%s" % e
             kwargs['message'] = m
-    
+
     return _HTTPErrorTemplate % kwargs
 
 
 def _be_ie_unfriendly(status):
     import cherrypy
     response = cherrypy.serving.response
-    
+
     # For some statuses, Internet Explorer 5+ shows "friendly error
     # messages" instead of our response.body if the body is smaller
     # than a given size. Fix this by returning a body over that size
 
 def bare_error(extrabody=None):
     """Produce status, headers, body for a critical error.
-    
+
     Returns a triple without calling any other questionable functions,
     so it should be as error-free as possible. Call it from an HTTP server
     if you get errors outside of the request.
-    
+
     If extrabody is None, a friendly but rather unhelpful error message
     is set in the body. If extrabody is a string, it will be appended
     as-is to the body.
     """
-    
+
     # The whole point of this function is to be a last line-of-defense
     # in handling errors. That is, it must not raise any errors itself;
     # it cannot be allowed to fail. Therefore, don't add to it!
     # In particular, don't call any other CP functions.
-    
+
     body = ntob("Unrecoverable error in the server.")
     if extrabody is not None:
         if not isinstance(extrabody, bytestr):
             extrabody = extrabody.encode('utf-8')
         body += ntob("\n") + extrabody
-    
+
     return (ntob("500 Internal Server Error"),
             [(ntob('Content-Type'), ntob('text/plain')),
              (ntob('Content-Length'), ntob(str(len(body)),'ISO-8859-1'))],
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.