Example #1
0
class Response(object):
    """An HTTP Response, including status, headers, and body."""

    status = ""
    """The HTTP Status-Code and Reason-Phrase."""

    header_list = []
    """
    A list of the HTTP response headers as (name, value) tuples.
    In general, you should use response.headers (a dict) instead. This
    attribute is generated from response.headers and is not valid until
    after the finalize phase."""

    headers = httputil.HeaderMap()
    """
    A dict-like object containing the response headers. Keys are header
    names (in Title-Case format); however, you may get and set them in
    a case-insensitive manner. That is, headers['Content-Type'] and
    headers['content-type'] refer to the same value. Values are header
    values (decoded according to :rfc:`2047` if necessary).
    
    .. seealso:: classes :class:`HeaderMap`, :class:`HeaderElement`
    """

    cookie = SimpleCookie()
    """See help(Cookie)."""

    body = ResponseBody()
    """The body (entity) of the HTTP response."""

    time = None
    """The value of time.time() when created. Use in HTTP dates."""

    timeout = 300
    """Seconds after which the response will be aborted."""

    timed_out = False
    """
    Flag to indicate the response should be aborted, because it has
    exceeded its timeout."""

    stream = False
    """If False, buffer the response body."""
    def __init__(self):
        self.status = None
        self.header_list = None
        self._body = []
        self.time = time.time()

        self.headers = httputil.HeaderMap()
        # Since we know all our keys are titled strings, we can
        # bypass HeaderMap.update and get a big speed boost.
        dict.update(
            self.headers, {
                "Content-Type": 'text/html',
                "Server": "CherryPy/" + cherrypy.__version__,
                "Date": httputil.HTTPDate(self.time),
            })
        self.cookie = SimpleCookie()

    def collapse_body(self):
        """Collapse self.body to a single string; replace it and return it."""
        if isinstance(self.body, basestring):
            return self.body

        newbody = []
        for chunk in self.body:
            if py3k and not isinstance(chunk, bytes):
                raise TypeError("Chunk %s is not of type 'bytes'." %
                                repr(chunk))
            newbody.append(chunk)
        newbody = ntob('').join(newbody)

        self.body = newbody
        return newbody

    def finalize(self):
        """Transform headers (and cookies) into self.header_list. (Core)"""
        try:
            code, reason, _ = httputil.valid_status(self.status)
        except ValueError:
            raise cherrypy.HTTPError(500, sys.exc_info()[1].args[0])

        headers = self.headers

        self.status = "%s %s" % (code, reason)
        self.output_status = ntob(str(code),
                                  'ascii') + ntob(" ") + headers.encode(reason)

        if self.stream:
            # The upshot: wsgiserver will chunk the response if
            # you pop Content-Length (or set it explicitly to None).
            # Note that lib.static sets C-L to the file's st_size.
            if dict.get(headers, 'Content-Length') is None:
                dict.pop(headers, 'Content-Length', None)
        elif code < 200 or code in (204, 205, 304):
            # "All 1xx (informational), 204 (no content),
            # and 304 (not modified) responses MUST NOT
            # include a message-body."
            dict.pop(headers, 'Content-Length', None)
            self.body = ntob("")
        else:
            # Responses which are not streamed should have a Content-Length,
            # but allow user code to set Content-Length if desired.
            if dict.get(headers, 'Content-Length') is None:
                content = self.collapse_body()
                dict.__setitem__(headers, 'Content-Length', len(content))

        # Transform our header dict into a list of tuples.
        self.header_list = h = headers.output()

        cookie = self.cookie.output()
        if cookie:
            for line in cookie.split("\n"):
                if line.endswith("\r"):
                    # Python 2.4 emits cookies joined by LF but 2.5+ by CRLF.
                    line = line[:-1]
                name, value = line.split(": ", 1)
                if isinstance(name, unicodestr):
                    name = name.encode("ISO-8859-1")
                if isinstance(value, unicodestr):
                    value = headers.encode(value)
                h.append((name, value))

    def check_timeout(self):
        """If now > self.time + self.timeout, set self.timed_out.
        
        This purposefully sets a flag, rather than raising an error,
        so that a monitor thread can interrupt the Response thread.
        """
        if time.time() > self.time + self.timeout:
            self.timed_out = True
Example #2
0
class Response(object):
    """An HTTP Response, including status, headers, and body."""

    status = ""
    """The HTTP Status-Code and Reason-Phrase."""

    header_list = []
    """
    A list of the HTTP response headers as (name, value) tuples.
    In general, you should use response.headers (a dict) instead. This
    attribute is generated from response.headers and is not valid until
    after the finalize phase."""

    headers = httputil.HeaderMap()
    """
    A dict-like object containing the response headers. Keys are header
    names (in Title-Case format); however, you may get and set them in
    a case-insensitive manner. That is, headers['Content-Type'] and
    headers['content-type'] refer to the same value. Values are header
    values (decoded according to :rfc:`2047` if necessary).

    .. seealso:: classes :class:`HeaderMap`, :class:`HeaderElement`
    """

    cookie = SimpleCookie()
    """See help(Cookie)."""

    body = ResponseBody()
    """The body (entity) of the HTTP response."""

    time = None
    """The value of time.time() when created. Use in HTTP dates."""

    timeout = 300
    """Seconds after which the response will be aborted."""

    timed_out = False
    """
    Flag to indicate the response should be aborted, because it has
    exceeded its timeout."""

    stream = False
    """If False, buffer the response body."""

    def __init__(self):
        self.status = None
        self.header_list = None
        self._body = []
        self.time = time.time()

        self.headers = httputil.HeaderMap()
        # Since we know all our keys are titled strings, we can
        # bypass HeaderMap.update and get a big speed boost.
        dict.update(
            self.headers,
            {
                "Content-Type": "text/html",
                "Server": "CherryPy/" + cherrypy.__version__,
                "Date": httputil.HTTPDate(self.time),
            },
        )
        self.cookie = SimpleCookie()

    def collapse_body(self):
        """Collapse self.body to a single string; replace it and return it."""
        if isinstance(self.body, basestring):
            return self.body

        newbody = []
        for chunk in self.body:
            if py3k and not isinstance(chunk, bytes):
                raise TypeError("Chunk %s is not of type 'bytes'." % repr(chunk))
            newbody.append(chunk)
        newbody = ntob("").join(newbody)

        self.body = newbody
        return newbody

    def finalize(self):
        """Transform headers (and cookies) into self.header_list. (Core)"""
        try:
            code, reason, _ = httputil.valid_status(self.status)
        except ValueError:
            raise cherrypy.HTTPError(500, sys.exc_info()[1].args[0])

        headers = self.headers

        self.status = "%s %s" % (code, reason)
        self.output_status = ntob(str(code), "ascii") + ntob(" ") + headers.encode(reason)

        if self.stream:
            # The upshot: wsgiserver will chunk the response if
            # you pop Content-Length (or set it explicitly to None).
            # Note that lib.static sets C-L to the file's st_size.
            if dict.get(headers, "Content-Length") is None:
                dict.pop(headers, "Content-Length", None)
        elif code < 200 or code in (204, 205, 304):
            # "All 1xx (informational), 204 (no content),
            # and 304 (not modified) responses MUST NOT
            # include a message-body."
            dict.pop(headers, "Content-Length", None)
            self.body = ntob("")
        else:
            # Responses which are not streamed should have a Content-Length,
            # but allow user code to set Content-Length if desired.
            if dict.get(headers, "Content-Length") is None:
                content = self.collapse_body()
                dict.__setitem__(headers, "Content-Length", len(content))

        # Transform our header dict into a list of tuples.
        self.header_list = h = headers.output()

        cookie = self.cookie.output()
        if cookie:
            for line in cookie.split("\n"):
                if line.endswith("\r"):
                    # Python 2.4 emits cookies joined by LF but 2.5+ by CRLF.
                    line = line[:-1]
                name, value = line.split(": ", 1)
                if isinstance(name, unicodestr):
                    name = name.encode("ISO-8859-1")
                if isinstance(value, unicodestr):
                    value = headers.encode(value)
                h.append((name, value))

    def check_timeout(self):
        """If now > self.time + self.timeout, set self.timed_out.

        This purposefully sets a flag, rather than raising an error,
        so that a monitor thread can interrupt the Response thread.
        """
        if time.time() > self.time + self.timeout:
            self.timed_out = True
Example #3
0
class Response(object):
    status = ''
    header_list = []
    headers = httputil.HeaderMap()
    cookie = SimpleCookie()
    body = ResponseBody()
    time = None
    timeout = 300
    timed_out = False
    stream = False

    def __init__(self):
        self.status = None
        self.header_list = None
        self._body = []
        self.time = time.time()
        self.headers = httputil.HeaderMap()
        dict.update(
            self.headers, {
                'Content-Type': 'text/html',
                'Server': 'CherryPy/' + cherrypy.__version__,
                'Date': httputil.HTTPDate(self.time)
            })
        self.cookie = SimpleCookie()

    def collapse_body(self):
        if isinstance(self.body, basestring):
            return self.body
        newbody = ''.join([chunk for chunk in self.body])
        self.body = newbody
        return newbody

    def finalize(self):
        try:
            code, reason, _ = httputil.valid_status(self.status)
        except ValueError:
            raise cherrypy.HTTPError(500, sys.exc_info()[1].args[0])

        headers = self.headers
        self.output_status = ntob(str(code),
                                  'ascii') + ntob(' ') + headers.encode(reason)
        if self.stream:
            if dict.get(headers, 'Content-Length') is None:
                dict.pop(headers, 'Content-Length', None)
        elif code < 200 or code in (204, 205, 304):
            dict.pop(headers, 'Content-Length', None)
            self.body = ntob('')
        elif dict.get(headers, 'Content-Length') is None:
            content = self.collapse_body()
            dict.__setitem__(headers, 'Content-Length', len(content))
        self.header_list = h = headers.output()
        cookie = self.cookie.output()
        if cookie:
            for line in cookie.split('\n'):
                if line.endswith('\r'):
                    line = line[:-1]
                name, value = line.split(': ', 1)
                if isinstance(name, unicodestr):
                    name = name.encode('ISO-8859-1')
                if isinstance(value, unicodestr):
                    value = headers.encode(value)
                h.append((name, value))

    def check_timeout(self):
        if time.time() > self.time + self.timeout:
            self.timed_out = True
class Response(object):
    status = ''
    header_list = []
    headers = httputil.HeaderMap()
    cookie = SimpleCookie()
    body = ResponseBody()
    time = None
    timeout = 300
    timed_out = False
    stream = False

    def __init__(self):
        self.status = None
        self.header_list = None
        self._body = []
        self.time = time.time()
        self.headers = httputil.HeaderMap()
        dict.update(self.headers, {'Content-Type': 'text/html',
         'Server': 'CherryPy/' + cherrypy.__version__,
         'Date': httputil.HTTPDate(self.time)})
        self.cookie = SimpleCookie()

    def collapse_body(self):
        if isinstance(self.body, basestring):
            return self.body
        newbody = ''.join([ chunk for chunk in self.body ])
        self.body = newbody
        return newbody

    def finalize(self):
        try:
            code, reason, _ = httputil.valid_status(self.status)
        except ValueError:
            raise cherrypy.HTTPError(500, sys.exc_info()[1].args[0])

        headers = self.headers
        self.output_status = ntob(str(code), 'ascii') + ntob(' ') + headers.encode(reason)
        if self.stream:
            if dict.get(headers, 'Content-Length') is None:
                dict.pop(headers, 'Content-Length', None)
        elif code < 200 or code in (204, 205, 304):
            dict.pop(headers, 'Content-Length', None)
            self.body = ntob('')
        elif dict.get(headers, 'Content-Length') is None:
            content = self.collapse_body()
            dict.__setitem__(headers, 'Content-Length', len(content))
        self.header_list = h = headers.output()
        cookie = self.cookie.output()
        if cookie:
            for line in cookie.split('\n'):
                if line.endswith('\r'):
                    line = line[:-1]
                name, value = line.split(': ', 1)
                if isinstance(name, unicodestr):
                    name = name.encode('ISO-8859-1')
                if isinstance(value, unicodestr):
                    value = headers.encode(value)
                h.append((name, value))

    def check_timeout(self):
        if time.time() > self.time + self.timeout:
            self.timed_out = True
Example #5
0
class Response(object):
    """An HTTP Response, including status, headers, and body."""
    status = ''
    header_list = []
    headers = httputil.HeaderMap()
    cookie = SimpleCookie()
    body = ResponseBody()
    time = None
    timeout = 300
    timed_out = False
    stream = False

    def __init__(self):
        self.status = None
        self.header_list = None
        self._body = []
        self.time = time.time()
        self.headers = httputil.HeaderMap()
        dict.update(
            self.headers, {
                'Content-Type': 'text/html',
                'Server': 'CherryPy/' + cherrypy.__version__,
                'Date': httputil.HTTPDate(self.time)
            })
        self.cookie = SimpleCookie()

    def collapse_body(self):
        """Collapse self.body to a single string; replace it and return it."""
        if isinstance(self.body, basestring):
            return self.body
        newbody = ''.join([chunk for chunk in self.body])
        self.body = newbody
        return newbody

    def finalize(self):
        """Transform headers (and cookies) into self.header_list. (Core)"""
        try:
            code, reason, _ = httputil.valid_status(self.status)
        except ValueError:
            raise cherrypy.HTTPError(500, sys.exc_info()[1].args[0])

        headers = self.headers
        self.output_status = ntob(str(code),
                                  'ascii') + ntob(' ') + headers.encode(reason)
        if self.stream:
            if dict.get(headers, 'Content-Length') is None:
                dict.pop(headers, 'Content-Length', None)
        elif code < 200 or code in (204, 205, 304):
            dict.pop(headers, 'Content-Length', None)
            self.body = ntob('')
        elif dict.get(headers, 'Content-Length') is None:
            content = self.collapse_body()
            dict.__setitem__(headers, 'Content-Length', len(content))
        self.header_list = h = headers.output()
        cookie = self.cookie.output()
        if cookie:
            for line in cookie.split('\n'):
                if line.endswith('\r'):
                    line = line[:-1]
                name, value = line.split(': ', 1)
                if isinstance(name, unicodestr):
                    name = name.encode('ISO-8859-1')
                if isinstance(value, unicodestr):
                    value = headers.encode(value)
                h.append((name, value))

    def check_timeout(self):
        """If now > self.time + self.timeout, set self.timed_out.
        
        This purposefully sets a flag, rather than raising an error,
        so that a monitor thread can interrupt the Response thread.
        """
        if time.time() > self.time + self.timeout:
            self.timed_out = True