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

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import Cookie
  5. import os
  6. import sys
  7. import time
  8. import types
  9. import cherrypy
  10. from cherrypy import _cpcgifs, _cpconfig
  11. from cherrypy._cperror import format_exc, bare_error
  12. from cherrypy.lib import http, file_generator
  13.  
  14. class Hook(object):
  15.     __metaclass__ = cherrypy._AttributeDocstrings
  16.     callback = None
  17.     callback__doc = '\n    The bare callable that this Hook object is wrapping, which will\n    be called when the Hook is called.'
  18.     failsafe = False
  19.     failsafe__doc = '\n    If True, the callback is guaranteed to run even if other callbacks\n    from the same call point raise exceptions.'
  20.     priority = 50
  21.     priority__doc = '\n    Defines the order of execution for a list of Hooks. Priority numbers\n    should be limited to the closed interval [0, 100], but values outside\n    this range are acceptable, as are fractional values.'
  22.     kwargs = { }
  23.     kwargs__doc = '\n    A set of keyword arguments that will be passed to the\n    callable on each call.'
  24.     
  25.     def __init__(self, callback, failsafe = None, priority = None, **kwargs):
  26.         self.callback = callback
  27.         if failsafe is None:
  28.             failsafe = getattr(callback, 'failsafe', False)
  29.         
  30.         self.failsafe = failsafe
  31.         if priority is None:
  32.             priority = getattr(callback, 'priority', 50)
  33.         
  34.         self.priority = priority
  35.         self.kwargs = kwargs
  36.  
  37.     
  38.     def __cmp__(self, other):
  39.         return cmp(self.priority, other.priority)
  40.  
  41.     
  42.     def __call__(self):
  43.         return self.callback(**self.kwargs)
  44.  
  45.     
  46.     def __repr__(self):
  47.         cls = self.__class__
  48.         return cls.__name__ % (self.callback, self.failsafe, self.priority, ', '.join, [], []([ '%s=%r' % (k, v) for k, v in self.kwargs.iteritems() ]))
  49.  
  50.  
  51.  
  52. class HookMap(dict):
  53.     
  54.     def __new__(cls, points = None):
  55.         d = dict.__new__(cls)
  56.         for p in []:
  57.             d[p] = []
  58.         return d
  59.  
  60.     
  61.     def __init__(self, *a, **kw):
  62.         pass
  63.  
  64.     
  65.     def attach(self, point, callback, failsafe = None, priority = None, **kwargs):
  66.         self[point].append(Hook(callback, failsafe, priority, **kwargs))
  67.  
  68.     
  69.     def run(self, point):
  70.         exc = None
  71.         hooks = self[point]
  72.         hooks.sort()
  73.         for hook in hooks:
  74.             if exc is None or hook.failsafe:
  75.                 
  76.                 try:
  77.                     hook()
  78.                 except (KeyboardInterrupt, SystemExit):
  79.                     raise 
  80.                 except (cherrypy.HTTPError, cherrypy.HTTPRedirect, cherrypy.InternalRedirect):
  81.                     exc = sys.exc_info()[1]
  82.                 except:
  83.                     None<EXCEPTION MATCH>(KeyboardInterrupt, SystemExit)
  84.                     exc = sys.exc_info()[1]
  85.                     cherrypy.log(traceback = True, severity = 40)
  86.                 
  87.  
  88.             None<EXCEPTION MATCH>(KeyboardInterrupt, SystemExit)
  89.         
  90.         if exc:
  91.             raise 
  92.         exc
  93.  
  94.     
  95.     def __copy__(self):
  96.         newmap = self.__class__()
  97.         for k, v in self.iteritems():
  98.             newmap[k] = v[:]
  99.         
  100.         return newmap
  101.  
  102.     copy = __copy__
  103.     
  104.     def __repr__(self):
  105.         cls = self.__class__
  106.         return '%s.%s(points=%r)' % (cls.__module__, cls.__name__, self.keys())
  107.  
  108.  
  109.  
  110. def hooks_namespace(k, v):
  111.     hookpoint = k.split('.', 1)[0]
  112.     if isinstance(v, basestring):
  113.         v = cherrypy.lib.attributes(v)
  114.     
  115.     if not isinstance(v, Hook):
  116.         v = Hook(v)
  117.     
  118.     cherrypy.request.hooks[hookpoint].append(v)
  119.  
  120.  
  121. def request_namespace(k, v):
  122.     setattr(cherrypy.request, k, v)
  123.  
  124.  
  125. def response_namespace(k, v):
  126.     setattr(cherrypy.response, k, v)
  127.  
  128.  
  129. def error_page_namespace(k, v):
  130.     if k != 'default':
  131.         k = int(k)
  132.     
  133.     cherrypy.request.error_page[k] = v
  134.  
  135. hookpoints = [
  136.     'on_start_resource',
  137.     'before_request_body',
  138.     'before_handler',
  139.     'before_finalize',
  140.     'on_end_resource',
  141.     'on_end_request',
  142.     'before_error_response',
  143.     'after_error_response']
  144.  
  145. class Request(object):
  146.     __metaclass__ = cherrypy._AttributeDocstrings
  147.     prev = None
  148.     prev__doc = '\n    The previous Request object (if any). This should be None\n    unless we are processing an InternalRedirect.'
  149.     local = http.Host('127.0.0.1', 80)
  150.     local__doc = 'An http.Host(ip, port, hostname) object for the server socket.'
  151.     remote = http.Host('127.0.0.1', 1111)
  152.     remote__doc = 'An http.Host(ip, port, hostname) object for the client socket.'
  153.     scheme = 'http'
  154.     scheme__doc = "\n    The protocol used between client and server. In most cases,\n    this will be either 'http' or 'https'."
  155.     server_protocol = 'HTTP/1.1'
  156.     server_protocol__doc = '\n    The HTTP version for which the HTTP server is at least\n    conditionally compliant.'
  157.     base = ''
  158.     base__doc = 'The (scheme://host) portion of the requested URL.'
  159.     request_line = ''
  160.     request_line__doc = '\n    The complete Request-Line received from the client. This is a\n    single string consisting of the request method, URI, and protocol\n    version (joined by spaces). Any final CRLF is removed.'
  161.     method = 'GET'
  162.     method__doc = '\n    Indicates the HTTP method to be performed on the resource identified\n    by the Request-URI. Common methods include GET, HEAD, POST, PUT, and\n    DELETE. CherryPy allows any extension method; however, various HTTP\n    servers and gateways may restrict the set of allowable methods.\n    CherryPy applications SHOULD restrict the set (on a per-URI basis).'
  163.     query_string = ''
  164.     query_string__doc = "\n    The query component of the Request-URI, a string of information to be\n    interpreted by the resource. The query portion of a URI follows the\n    path component, and is separated by a '?'. For example, the URI\n    'http://www.cherrypy.org/wiki?a=3&b=4' has the query component,\n    'a=3&b=4'."
  165.     protocol = (1, 1)
  166.     protocol__doc = "The HTTP protocol version corresponding to the set\n        of features which should be allowed in the response. If BOTH\n        the client's request message AND the server's level of HTTP\n        compliance is HTTP/1.1, this attribute will be the tuple (1, 1).\n        If either is 1.0, this attribute will be the tuple (1, 0).\n        Lower HTTP protocol versions are not explicitly supported."
  167.     params = { }
  168.     params__doc = "\n    A dict which combines query string (GET) and request entity (POST)\n    variables. This is populated in two stages: GET params are added\n    before the 'on_start_resource' hook, and POST params are added\n    between the 'before_request_body' and 'before_handler' hooks."
  169.     header_list = []
  170.     header_list__doc = '\n    A list of the HTTP request headers as (name, value) tuples.\n    In general, you should use request.headers (a dict) instead.'
  171.     headers = http.HeaderMap()
  172.     headers__doc = "\n    A dict-like object containing the request headers. Keys are header\n    names (in Title-Case format); however, you may get and set them in\n    a case-insensitive manner. That is, headers['Content-Type'] and\n    headers['content-type'] refer to the same value. Values are header\n    values (decoded according to RFC 2047 if necessary). See also:\n    http.HeaderMap, http.HeaderElement."
  173.     cookie = Cookie.SimpleCookie()
  174.     cookie__doc = 'See help(Cookie).'
  175.     rfile = None
  176.     rfile__doc = "\n    If the request included an entity (body), it will be available\n    as a stream in this attribute. However, the rfile will normally\n    be read for you between the 'before_request_body' hook and the\n    'before_handler' hook, and the resulting string is placed into\n    either request.params or the request.body attribute.\n    \n    You may disable the automatic consumption of the rfile by setting\n    request.process_request_body to False, either in config for the desired\n    path, or in an 'on_start_resource' or 'before_request_body' hook.\n    \n    WARNING: In almost every case, you should not attempt to read from the\n    rfile stream after CherryPy's automatic mechanism has read it. If you\n    turn off the automatic parsing of rfile, you should read exactly the\n    number of bytes specified in request.headers['Content-Length'].\n    Ignoring either of these warnings may result in a hung request thread\n    or in corruption of the next (pipelined) request.\n    "
  177.     process_request_body = True
  178.     process_request_body__doc = '\n    If True, the rfile (if any) is automatically read and parsed,\n    and the result placed into request.params or request.body.'
  179.     methods_with_bodies = ('POST', 'PUT')
  180.     methods_with_bodies__doc = '\n    A sequence of HTTP methods for which CherryPy will automatically\n    attempt to read a body from the rfile.'
  181.     body = None
  182.     body__doc = "\n    If the request Content-Type is 'application/x-www-form-urlencoded'\n    or multipart, this will be None. Otherwise, this will contain the\n    request entity body as a string; this value is set between the\n    'before_request_body' and 'before_handler' hooks (assuming that\n    process_request_body is True)."
  183.     body_params = None
  184.     body_params__doc = '\n    If the request Content-Type is \'application/x-www-form-urlencoded\' or\n    multipart, this will be a dict of the params pulled from the entity\n    body; that is, it will be the portion of request.params that come\n    from the message body (sometimes called "POST params", although they\n    can be sent with various HTTP method verbs). This value is set between\n    the \'before_request_body\' and \'before_handler\' hooks (assuming that\n    process_request_body is True).'
  185.     dispatch = cherrypy.dispatch.Dispatcher()
  186.     dispatch__doc = "\n    The object which looks up the 'page handler' callable and collects\n    config for the current request based on the path_info, other\n    request attributes, and the application architecture. The core\n    calls the dispatcher as early as possible, passing it a 'path_info'\n    argument.\n    \n    The default dispatcher discovers the page handler by matching path_info\n    to a hierarchical arrangement of objects, starting at request.app.root.\n    See help(cherrypy.dispatch) for more information."
  187.     script_name = ''
  188.     script_name__doc = '\n    The \'mount point\' of the application which is handling this request.\n    \n    This attribute MUST NOT end in a slash. If the script_name refers to\n    the root of the URI, it MUST be an empty string (not "/").\n    '
  189.     path_info = '/'
  190.     path_info__doc = "\n    The 'relative path' portion of the Request-URI. This is relative\n    to the script_name ('mount point') of the application which is\n    handling this request."
  191.     login = None
  192.     login__doc = "\n    When authentication is used during the request processing this is\n    set to 'False' if it failed and to the 'username' value if it succeeded.\n    The default 'None' implies that no authentication happened."
  193.     app = None
  194.     app__doc = 'The cherrypy.Application object which is handling this request.'
  195.     handler = None
  196.     handler__doc = '\n    The function, method, or other callable which CherryPy will call to\n    produce the response. The discovery of the handler and the arguments\n    it will receive are determined by the request.dispatch object.\n    By default, the handler is discovered by walking a tree of objects\n    starting at request.app.root, and is then passed all HTTP params\n    (from the query string and POST body) as keyword arguments.'
  197.     toolmaps = { }
  198.     toolmaps__doc = '\n    A nested dict of all Toolboxes and Tools in effect for this request,\n    of the form: {Toolbox.namespace: {Tool.name: config dict}}.'
  199.     config = None
  200.     config__doc = '\n    A flat dict of all configuration entries which apply to the\n    current request. These entries are collected from global config,\n    application config (based on request.path_info), and from handler\n    config (exactly how is governed by the request.dispatch object in\n    effect for this request; by default, handler config can be attached\n    anywhere in the tree between request.app.root and the final handler,\n    and inherits downward).'
  201.     is_index = None
  202.     is_index__doc = "\n    This will be True if the current request is mapped to an 'index'\n    resource handler (also, a 'default' handler if path_info ends with\n    a slash). The value may be used to automatically redirect the\n    user-agent to a 'more canonical' URL which either adds or removes\n    the trailing slash. See cherrypy.tools.trailing_slash."
  203.     hooks = HookMap(hookpoints)
  204.     hooks__doc = '\n    A HookMap (dict-like object) of the form: {hookpoint: [hook, ...]}.\n    Each key is a str naming the hook point, and each value is a list\n    of hooks which will be called at that hook point during this request.\n    The list of hooks is generally populated as early as possible (mostly\n    from Tools specified in config), but may be extended at any time.\n    See also: _cprequest.Hook, _cprequest.HookMap, and cherrypy.tools.'
  205.     error_response = cherrypy.HTTPError(500).set_response
  206.     error_response__doc = '\n    The no-arg callable which will handle unexpected, untrapped errors\n    during request processing. This is not used for expected exceptions\n    (like NotFound, HTTPError, or HTTPRedirect) which are raised in\n    response to expected conditions (those should be customized either\n    via request.error_page or by overriding HTTPError.set_response).\n    By default, error_response uses HTTPError(500) to return a generic\n    error response to the user-agent.'
  207.     error_page = { }
  208.     error_page__doc = "\n    A dict of {error code: response filename or callable} pairs.\n    \n    The error code must be an int representing a given HTTP error code,\n    or the string 'default', which will be used if no matching entry\n    is found for a given numeric code.\n    \n    If a filename is provided, the file should contain a Python string-\n    formatting template, and can expect by default to receive format \n    values with the mapping keys %(status)s, %(message)s, %(traceback)s,\n    and %(version)s. The set of format mappings can be extended by\n    overriding HTTPError.set_response.\n    \n    If a callable is provided, it will be called by default with keyword \n    arguments 'status', 'message', 'traceback', and 'version', as for a\n    string-formatting template. The callable must return a string which\n    will be set to response.body. It may also override headers or perform\n    any other processing.\n    \n    If no entry is given for an error code, and no 'default' entry exists,\n    a default template will be used.\n    "
  209.     show_tracebacks = True
  210.     show_tracebacks__doc = '\n    If True, unexpected errors encountered during request processing will\n    include a traceback in the response body.'
  211.     throws = (KeyboardInterrupt, SystemExit, cherrypy.InternalRedirect)
  212.     throws__doc = 'The sequence of exceptions which Request.run does not trap.'
  213.     throw_errors = False
  214.     throw_errors__doc = "\n    If True, Request.run will not trap any errors (except HTTPRedirect and\n    HTTPError, which are more properly called 'exceptions', not errors)."
  215.     closed = False
  216.     closed__doc = '\n    True once the close method has been called, False otherwise.'
  217.     stage = None
  218.     stage__doc = '\n    A string containing the stage reached in the request-handling process.\n    This is useful when debugging a live server with hung requests.'
  219.     namespaces = _cpconfig.NamespaceSet(**{
  220.         'hooks': hooks_namespace,
  221.         'request': request_namespace,
  222.         'response': response_namespace,
  223.         'error_page': error_page_namespace,
  224.         'tools': cherrypy.tools })
  225.     
  226.     def __init__(self, local_host, remote_host, scheme = 'http', server_protocol = 'HTTP/1.1'):
  227.         self.local = local_host
  228.         self.remote = remote_host
  229.         self.scheme = scheme
  230.         self.server_protocol = server_protocol
  231.         self.closed = False
  232.         self.error_page = self.error_page.copy()
  233.         self.namespaces = self.namespaces.copy()
  234.         self.stage = None
  235.  
  236.     
  237.     def close(self):
  238.         if not self.closed:
  239.             self.closed = True
  240.             self.stage = 'on_end_request'
  241.             self.hooks.run('on_end_request')
  242.             self.stage = 'close'
  243.         
  244.  
  245.     
  246.     def run(self, method, path, query_string, req_protocol, headers, rfile):
  247.         self.stage = 'run'
  248.         
  249.         try:
  250.             self.error_response = cherrypy.HTTPError(500).set_response
  251.             self.method = method
  252.             if not path:
  253.                 pass
  254.             path = '/'
  255.             if not query_string:
  256.                 pass
  257.             self.query_string = ''
  258.             rp = (int(req_protocol[5]), int(req_protocol[7]))
  259.             sp = (int(self.server_protocol[5]), int(self.server_protocol[7]))
  260.             self.protocol = min(rp, sp)
  261.             url = path
  262.             if query_string:
  263.                 url += '?' + query_string
  264.             
  265.             self.request_line = '%s %s %s' % (method, url, req_protocol)
  266.             self.header_list = list(headers)
  267.             self.rfile = rfile
  268.             self.headers = http.HeaderMap()
  269.             self.cookie = Cookie.SimpleCookie()
  270.             self.handler = None
  271.             self.script_name = self.app.script_name
  272.             self.path_info = pi = path[len(self.script_name):]
  273.             self.stage = 'respond'
  274.             self.respond(pi)
  275.         except self.throws:
  276.             raise 
  277.         except:
  278.             if self.throw_errors:
  279.                 raise 
  280.             self.throw_errors
  281.             cherrypy.log(traceback = True, severity = 40)
  282.             if self.show_tracebacks:
  283.                 body = format_exc()
  284.             else:
  285.                 body = ''
  286.             r = bare_error(body)
  287.             response = cherrypy.response
  288.             (response.status, response.header_list, response.body) = r
  289.  
  290.         if self.method == 'HEAD':
  291.             cherrypy.response.body = []
  292.         
  293.         cherrypy.log.access()
  294.         if cherrypy.response.timed_out:
  295.             raise cherrypy.TimeoutError()
  296.         cherrypy.response.timed_out
  297.         return cherrypy.response
  298.  
  299.     
  300.     def respond(self, path_info):
  301.         
  302.         try:
  303.             
  304.             try:
  305.                 if self.app is None:
  306.                     raise cherrypy.NotFound()
  307.                 self.app is None
  308.                 self.stage = 'process_headers'
  309.                 self.process_headers()
  310.                 self.hooks = self.__class__.hooks.copy()
  311.                 self.toolmaps = { }
  312.                 self.stage = 'get_resource'
  313.                 self.get_resource(path_info)
  314.                 self.namespaces(self.config)
  315.                 self.stage = 'on_start_resource'
  316.                 self.hooks.run('on_start_resource')
  317.                 if self.process_request_body:
  318.                     if self.method not in self.methods_with_bodies:
  319.                         self.process_request_body = False
  320.                     
  321.                 
  322.                 self.stage = 'before_request_body'
  323.                 self.hooks.run('before_request_body')
  324.                 if self.process_request_body:
  325.                     self.process_body()
  326.                 
  327.                 self.stage = 'before_handler'
  328.                 self.hooks.run('before_handler')
  329.                 if self.handler:
  330.                     self.stage = 'handler'
  331.                     cherrypy.response.body = self.handler()
  332.                 
  333.                 self.stage = 'before_finalize'
  334.                 self.hooks.run('before_finalize')
  335.                 cherrypy.response.finalize()
  336.             except (cherrypy.HTTPRedirect, cherrypy.HTTPError):
  337.                 inst = None
  338.                 inst.set_response()
  339.                 self.stage = 'before_finalize (HTTPError)'
  340.                 self.hooks.run('before_finalize')
  341.                 cherrypy.response.finalize()
  342.             finally:
  343.                 self.stage = 'on_end_resource'
  344.                 self.hooks.run('on_end_resource')
  345.  
  346.         except self.throws:
  347.             raise 
  348.         except:
  349.             if self.throw_errors:
  350.                 raise 
  351.             self.throw_errors
  352.             self.handle_error()
  353.  
  354.  
  355.     
  356.     def process_headers(self):
  357.         self.params = http.parse_query_string(self.query_string)
  358.         headers = self.headers
  359.         for name, value in self.header_list:
  360.             name = name.title()
  361.             value = value.strip()
  362.             if '=?' in value:
  363.                 dict.__setitem__(headers, name, http.decode_TEXT(value))
  364.             else:
  365.                 dict.__setitem__(headers, name, value)
  366.             if name == 'Cookie':
  367.                 
  368.                 try:
  369.                     self.cookie.load(value)
  370.                 except Cookie.CookieError:
  371.                     msg = 'Illegal cookie name %s' % value.split('=')[0]
  372.                     raise cherrypy.HTTPError(400, msg)
  373.                 except:
  374.                     None<EXCEPTION MATCH>Cookie.CookieError
  375.                 
  376.  
  377.             None<EXCEPTION MATCH>Cookie.CookieError
  378.         
  379.         if not dict.__contains__(headers, 'Host'):
  380.             if self.protocol >= (1, 1):
  381.                 msg = "HTTP/1.1 requires a 'Host' request header."
  382.                 raise cherrypy.HTTPError(400, msg)
  383.             self.protocol >= (1, 1)
  384.         
  385.         host = dict.get(headers, 'Host')
  386.         if not host:
  387.             if not self.local.name:
  388.                 pass
  389.             host = self.local.ip
  390.         
  391.         self.base = '%s://%s' % (self.scheme, host)
  392.  
  393.     
  394.     def get_resource(self, path):
  395.         dispatch = self.dispatch
  396.         if not path:
  397.             pass
  398.         trail = '/'
  399.         while trail:
  400.             nodeconf = self.app.config.get(trail, { })
  401.             d = nodeconf.get('request.dispatch')
  402.             if d:
  403.                 dispatch = d
  404.                 break
  405.             
  406.             lastslash = trail.rfind('/')
  407.             if lastslash == -1:
  408.                 break
  409.                 continue
  410.             if lastslash == 0 and trail != '/':
  411.                 trail = '/'
  412.                 continue
  413.             trail = trail[:lastslash]
  414.         dispatch(path)
  415.  
  416.     
  417.     def process_body(self):
  418.         if not self.headers.get('Content-Length', ''):
  419.             raise cherrypy.HTTPError(411)
  420.         self.headers.get('Content-Length', '')
  421.         if 'Content-Type' not in self.headers:
  422.             h = http.HeaderMap(self.headers.items())
  423.             h['Content-Type'] = ''
  424.         else:
  425.             h = self.headers
  426.         
  427.         try:
  428.             forms = _cpcgifs.FieldStorage(fp = self.rfile, headers = h, environ = {
  429.                 'REQUEST_METHOD': 'POST' }, keep_blank_values = 1)
  430.         except Exception:
  431.             e = None
  432.             if e.__class__.__name__ == 'MaxSizeExceeded':
  433.                 raise cherrypy.HTTPError(413)
  434.             e.__class__.__name__ == 'MaxSizeExceeded'
  435.             raise 
  436.  
  437.         if forms.file:
  438.             self.body = forms.file
  439.         else:
  440.             self.body_params = p = http.params_from_CGI_form(forms)
  441.             self.params.update(p)
  442.  
  443.     
  444.     def handle_error(self):
  445.         
  446.         try:
  447.             self.hooks.run('before_error_response')
  448.             if self.error_response:
  449.                 self.error_response()
  450.             
  451.             self.hooks.run('after_error_response')
  452.             cherrypy.response.finalize()
  453.         except cherrypy.HTTPRedirect:
  454.             inst = None
  455.             inst.set_response()
  456.             cherrypy.response.finalize()
  457.  
  458.  
  459.  
  460.  
  461. class Body(object):
  462.     
  463.     def __get__(self, obj, objclass = None):
  464.         if obj is None:
  465.             return self
  466.         return obj._body
  467.  
  468.     
  469.     def __set__(self, obj, value):
  470.         if isinstance(value, basestring):
  471.             if value:
  472.                 value = [
  473.                     value]
  474.             else:
  475.                 value = []
  476.         elif isinstance(value, types.FileType):
  477.             value = file_generator(value)
  478.         elif value is None:
  479.             value = []
  480.         
  481.         obj._body = value
  482.  
  483.  
  484.  
  485. class Response(object):
  486.     __metaclass__ = cherrypy._AttributeDocstrings
  487.     status = ''
  488.     status__doc = 'The HTTP Status-Code and Reason-Phrase.'
  489.     header_list = []
  490.     header_list__doc = '\n    A list of the HTTP response headers as (name, value) tuples.\n    In general, you should use response.headers (a dict) instead.'
  491.     headers = http.HeaderMap()
  492.     headers__doc = "\n    A dict-like object containing the response headers. Keys are header\n    names (in Title-Case format); however, you may get and set them in\n    a case-insensitive manner. That is, headers['Content-Type'] and\n    headers['content-type'] refer to the same value. Values are header\n    values (decoded according to RFC 2047 if necessary). See also:\n    http.HeaderMap, http.HeaderElement."
  493.     cookie = Cookie.SimpleCookie()
  494.     cookie__doc = 'See help(Cookie).'
  495.     body = Body()
  496.     body__doc = 'The body (entity) of the HTTP response.'
  497.     time = None
  498.     time__doc = 'The value of time.time() when created. Use in HTTP dates.'
  499.     timeout = 300
  500.     timeout__doc = 'Seconds after which the response will be aborted.'
  501.     timed_out = False
  502.     timed_out__doc = '\n    Flag to indicate the response should be aborted, because it has\n    exceeded its timeout.'
  503.     stream = False
  504.     stream__doc = 'If False, buffer the response body.'
  505.     
  506.     def __init__(self):
  507.         self.status = None
  508.         self.header_list = None
  509.         self._body = []
  510.         self.time = time.time()
  511.         self.headers = http.HeaderMap()
  512.         dict.update(self.headers, {
  513.             'Content-Type': 'text/html',
  514.             'Server': 'CherryPy/' + cherrypy.__version__,
  515.             'Date': http.HTTPDate(self.time) })
  516.         self.cookie = Cookie.SimpleCookie()
  517.  
  518.     
  519.     def collapse_body(self):
  520.         newbody = []([ chunk for chunk in self.body ])
  521.         self.body = newbody
  522.         return newbody
  523.  
  524.     
  525.     def finalize(self):
  526.         
  527.         try:
  528.             (code, reason, _) = http.valid_status(self.status)
  529.         except ValueError:
  530.             x = None
  531.             raise cherrypy.HTTPError(500, x.args[0])
  532.  
  533.         self.status = '%s %s' % (code, reason)
  534.         headers = self.headers
  535.         if self.stream:
  536.             if dict.get(headers, 'Content-Length') is None:
  537.                 dict.pop(headers, 'Content-Length', None)
  538.             
  539.         elif code < 200 or code in (204, 205, 304):
  540.             dict.pop(headers, 'Content-Length', None)
  541.             self.body = ''
  542.         elif dict.get(headers, 'Content-Length') is None:
  543.             content = self.collapse_body()
  544.             dict.__setitem__(headers, 'Content-Length', len(content))
  545.         
  546.         self.header_list = h = headers.output(cherrypy.request.protocol)
  547.         cookie = self.cookie.output()
  548.         if cookie:
  549.             for line in cookie.split('\n'):
  550.                 if line.endswith('\r'):
  551.                     line = line[:-1]
  552.                 
  553.                 (name, value) = line.split(': ', 1)
  554.                 h.append((name, value))
  555.             
  556.         
  557.  
  558.     
  559.     def check_timeout(self):
  560.         if time.time() > self.time + self.timeout:
  561.             self.timed_out = True
  562.         
  563.  
  564.  
  565.