home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_1489 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  9.1 KB  |  275 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. from cgi import escape as _escape
  5. from sys import exc_info as _exc_info
  6. from traceback import format_exception as _format_exception
  7. from urlparse import urljoin as _urljoin
  8. from cherrypy.lib import http as _http
  9.  
  10. class CherryPyException(Exception):
  11.     pass
  12.  
  13.  
  14. class TimeoutError(CherryPyException):
  15.     pass
  16.  
  17.  
  18. class InternalRedirect(CherryPyException):
  19.     
  20.     def __init__(self, path):
  21.         import cherrypy
  22.         request = cherrypy.request
  23.         self.query_string = ''
  24.         if '?' in path:
  25.             (path, self.query_string) = path.split('?', 1)
  26.         
  27.         path = _urljoin(request.path_info, path)
  28.         self.path = path
  29.         CherryPyException.__init__(self, path, self.query_string)
  30.  
  31.  
  32.  
  33. class HTTPRedirect(CherryPyException):
  34.     
  35.     def __init__(self, urls, status = None):
  36.         import cherrypy
  37.         request = cherrypy.request
  38.         if isinstance(urls, basestring):
  39.             urls = [
  40.                 urls]
  41.         
  42.         abs_urls = []
  43.         for url in urls:
  44.             url = _urljoin(cherrypy.url(), url)
  45.             abs_urls.append(url)
  46.         
  47.         self.urls = abs_urls
  48.         if status is None:
  49.             if request.protocol >= (1, 1):
  50.                 status = 303
  51.             else:
  52.                 status = 302
  53.         else:
  54.             status = int(status)
  55.             if status < 300 or status > 399:
  56.                 raise ValueError('status must be between 300 and 399.')
  57.             status > 399
  58.         self.status = status
  59.         CherryPyException.__init__(self, abs_urls, status)
  60.  
  61.     
  62.     def set_response(self):
  63.         import cherrypy
  64.         response = cherrypy.response
  65.         response.status = status = self.status
  66.         if status in (300, 301, 302, 303, 307):
  67.             response.headers['Content-Type'] = 'text/html'
  68.             response.headers['Location'] = self.urls[0]
  69.             msg = {
  70.                 300: "This resource can be found at <a href='%s'>%s</a>.",
  71.                 301: "This resource has permanently moved to <a href='%s'>%s</a>.",
  72.                 302: "This resource resides temporarily at <a href='%s'>%s</a>.",
  73.                 303: "This resource can be found at <a href='%s'>%s</a>.",
  74.                 307: "This resource has moved temporarily to <a href='%s'>%s</a>." }[status]
  75.             response.body = []([ msg % (u, u) for u in self.urls ])
  76.             response.headers.pop('Content-Length', None)
  77.         elif status == 304:
  78.             for key in ('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-Location', 'Content-MD5', 'Content-Range', 'Content-Type', 'Expires', 'Last-Modified'):
  79.                 if key in response.headers:
  80.                     del response.headers[key]
  81.                     continue
  82.                 '<br />\n'.join
  83.             
  84.             response.body = None
  85.             response.headers.pop('Content-Length', None)
  86.         elif status == 305:
  87.             response.headers['Location'] = self.urls[0]
  88.             response.body = None
  89.             response.headers.pop('Content-Length', None)
  90.         else:
  91.             raise ValueError('The %s status code is unknown.' % status)
  92.         return '<br />\n'.join
  93.  
  94.     
  95.     def __call__(self):
  96.         raise self
  97.  
  98.  
  99.  
  100. def clean_headers(status):
  101.     import cherrypy
  102.     response = cherrypy.response
  103.     respheaders = response.headers
  104.     for key in [
  105.         'Accept-Ranges',
  106.         'Age',
  107.         'ETag',
  108.         'Location',
  109.         'Retry-After',
  110.         'Vary',
  111.         'Content-Encoding',
  112.         'Content-Length',
  113.         'Expires',
  114.         'Content-Location',
  115.         'Content-MD5',
  116.         'Last-Modified']:
  117.         if respheaders.has_key(key):
  118.             del respheaders[key]
  119.             continue
  120.     
  121.     if status != 416:
  122.         if respheaders.has_key('Content-Range'):
  123.             del respheaders['Content-Range']
  124.         
  125.     
  126.  
  127.  
  128. class HTTPError(CherryPyException):
  129.     
  130.     def __init__(self, status = 500, message = None):
  131.         self.status = status = int(status)
  132.         if status < 400 or status > 599:
  133.             raise ValueError('status must be between 400 and 599.')
  134.         status > 599
  135.         self._message = message
  136.         CherryPyException.__init__(self, status, message)
  137.  
  138.     
  139.     def set_response(self):
  140.         import cherrypy
  141.         response = cherrypy.response
  142.         clean_headers(self.status)
  143.         response.status = self.status
  144.         tb = None
  145.         if cherrypy.request.show_tracebacks:
  146.             tb = format_exc()
  147.         
  148.         response.headers['Content-Type'] = 'text/html'
  149.         content = self.get_error_page(self.status, traceback = tb, message = self._message)
  150.         response.body = content
  151.         response.headers['Content-Length'] = len(content)
  152.         _be_ie_unfriendly(self.status)
  153.  
  154.     
  155.     def get_error_page(self, *args, **kwargs):
  156.         return get_error_page(*args, **kwargs)
  157.  
  158.     
  159.     def __call__(self):
  160.         raise self
  161.  
  162.  
  163.  
  164. class NotFound(HTTPError):
  165.     
  166.     def __init__(self, path = None):
  167.         if path is None:
  168.             import cherrypy
  169.             path = cherrypy.request.script_name + cherrypy.request.path_info
  170.         
  171.         self.args = (path,)
  172.         HTTPError.__init__(self, 404, 'The path %r was not found.' % path)
  173.  
  174.  
  175. _HTTPErrorTemplate = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\n"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html>\n<head>\n    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>\n    <title>%(status)s</title>\n    <style type="text/css">\n    #powered_by {\n        margin-top: 20px;\n        border-top: 2px solid black;\n        font-style: italic;\n    }\n\n    #traceback {\n        color: red;\n    }\n    </style>\n</head>\n    <body>\n        <h2>%(status)s</h2>\n        <p>%(message)s</p>\n        <pre id="traceback">%(traceback)s</pre>\n    <div id="powered_by">\n    <span>Powered by <a href="http://www.cherrypy.org">CherryPy %(version)s</a></span>\n    </div>\n    </body>\n</html>\n'
  176.  
  177. def get_error_page(status, **kwargs):
  178.     import cherrypy
  179.     
  180.     try:
  181.         (code, reason, message) = _http.valid_status(status)
  182.     except ValueError:
  183.         x = None
  184.         raise cherrypy.HTTPError(500, x.args[0])
  185.  
  186.     if kwargs.get('status') is None:
  187.         kwargs['status'] = '%s %s' % (code, reason)
  188.     
  189.     if kwargs.get('message') is None:
  190.         kwargs['message'] = message
  191.     
  192.     if kwargs.get('traceback') is None:
  193.         kwargs['traceback'] = ''
  194.     
  195.     if kwargs.get('version') is None:
  196.         kwargs['version'] = cherrypy.__version__
  197.     
  198.     for k, v in kwargs.iteritems():
  199.         if v is None:
  200.             kwargs[k] = ''
  201.             continue
  202.         kwargs[k] = _escape(kwargs[k])
  203.     
  204.     pages = cherrypy.request.error_page
  205.     if not pages.get(code):
  206.         pass
  207.     error_page = pages.get('default')
  208.     if error_page:
  209.         
  210.         try:
  211.             if callable(error_page):
  212.                 return error_page(**kwargs)
  213.             return file(error_page, 'rb').read() % kwargs
  214.         e = _format_exception(*_exc_info())[-1]
  215.         m = kwargs['message']
  216.         if m:
  217.             m += '<br />'
  218.         
  219.  
  220.         m += 'In addition, the custom error page failed:\n<br />%s' % e
  221.         kwargs['message'] = m
  222.     
  223.     error_page
  224.     return _HTTPErrorTemplate % kwargs
  225.  
  226. _ie_friendly_error_sizes = {
  227.     400: 512,
  228.     403: 256,
  229.     404: 512,
  230.     405: 256,
  231.     406: 512,
  232.     408: 512,
  233.     409: 512,
  234.     410: 256,
  235.     500: 512,
  236.     501: 512,
  237.     505: 512 }
  238.  
  239. def _be_ie_unfriendly(status):
  240.     import cherrypy
  241.     response = cherrypy.response
  242.     s = _ie_friendly_error_sizes.get(status, 0)
  243.     if s:
  244.         s += 1
  245.         content = response.collapse_body()
  246.         l = len(content)
  247.         if l and l < s:
  248.             content = content + ' ' * (s - l)
  249.         
  250.         response.body = content
  251.         response.headers['Content-Length'] = len(content)
  252.     
  253.  
  254.  
  255. def format_exc(exc = None):
  256.     if exc is None:
  257.         exc = _exc_info()
  258.     
  259.     if exc == (None, None, None):
  260.         return ''
  261.     import traceback
  262.     return ''.join(traceback.format_exception(*exc))
  263.  
  264.  
  265. def bare_error(extrabody = None):
  266.     body = 'Unrecoverable error in the server.'
  267.     if extrabody is not None:
  268.         body += '\n' + extrabody
  269.     
  270.     return ('500 Internal Server Error', [
  271.         ('Content-Type', 'text/plain'),
  272.         ('Content-Length', str(len(body)))], [
  273.         body])
  274.  
  275.