Python cherrypy.response() Examples

The following are 30 code examples of cherrypy.response(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cherrypy , or try the search function .
Example #1
Source File: _cperror.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def clean_headers(status):
    """Remove any headers which should not apply to an error response."""
    response = cherrypy.serving.response

    # Remove headers which applied to the original content,
    # but do not apply to the error page.
    respheaders = response.headers
    for key in ['Accept-Ranges', 'Age', 'ETag', 'Location', 'Retry-After',
                'Vary', 'Content-Encoding', 'Content-Length', 'Expires',
                '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
        # with a byte-range-resp-spec of "*". The instance-length
        # specifies the current length of the selected resource.
        # A response with status code 206 (Partial Content) MUST NOT
        # include a Content-Range field with a byte-range- resp-spec of "*".
        if 'Content-Range' in respheaders:
            del respheaders['Content-Range'] 
Example #2
Source File: benchmark.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def run(self, method, path, query_string, protocol, headers, rfile):
        cherrypy.response.status = '200 OK'
        cherrypy.response.header_list = [('Content-Type', 'text/html'),
                                         ('Server', 'Null CherryPy'),
                                         ('Date', httputil.HTTPDate()),
                                         ('Content-Length', '0'),
                                         ]
        cherrypy.response.body = ['']
        return cherrypy.response 
Example #3
Source File: benchmark.py    From moviegrabber with GNU General Public License v3.0 6 votes vote down vote up
def run_standard_benchmarks():
    print("")
    print("Client Thread Report (1000 requests, 14 byte response body, "
           "%s server threads):" % cherrypy.server.thread_pool)
    print_report(thread_report())
    
    print("")
    print("Client Thread Report (1000 requests, 14 bytes via staticdir, "
           "%s server threads):" % cherrypy.server.thread_pool)
    print_report(thread_report("%s/static/index.html" % SCRIPT_NAME))
    
    print("")
    print("Size Report (1000 requests, 50 client threads, "
           "%s server threads):" % cherrypy.server.thread_pool)
    print_report(size_report())


#                         modpython and other WSGI                         # 
Example #4
Source File: _cpchecker.py    From moviegrabber with GNU General Public License v3.0 6 votes vote down vote up
def _populate_known_types(self):
        b = [x for x in vars(builtins).values()
             if type(x) is type(str)]
        
        def traverse(obj, namespace):
            for name in dir(obj):
                # Hack for 3.2's warning about body_params
                if name == 'body_params':
                    continue
                vtype = type(getattr(obj, name, None))
                if vtype in b:
                    self.known_config_types[namespace + "." + name] = vtype
        
        traverse(cherrypy.request, "request")
        traverse(cherrypy.response, "response")
        traverse(cherrypy.server, "server")
        traverse(cherrypy.engine, "engine")
        traverse(cherrypy.log, "log") 
Example #5
Source File: _cperror.py    From moviegrabber with GNU General Public License v3.0 6 votes vote down vote up
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
    for key in ["Accept-Ranges", "Age", "ETag", "Location", "Retry-After",
                "Vary", "Content-Encoding", "Content-Length", "Expires",
                "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
        # with a byte-range-resp-spec of "*". The instance-length
        # specifies the current length of the selected resource.
        # A response with status code 206 (Partial Content) MUST NOT
        # include a Content-Range field with a byte-range- resp-spec of "*".
        if "Content-Range" in respheaders:
            del respheaders["Content-Range"] 
Example #6
Source File: benchmark.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def run_standard_benchmarks():
    print('')
    print('Client Thread Report (1000 requests, 14 byte response body, '
          '%s server threads):' % cherrypy.server.thread_pool)
    print_report(thread_report())

    print('')
    print('Client Thread Report (1000 requests, 14 bytes via staticdir, '
          '%s server threads):' % cherrypy.server.thread_pool)
    print_report(thread_report('%s/static/index.html' % SCRIPT_NAME))

    print('')
    print('Size Report (1000 requests, 50 client threads, '
          '%s server threads):' % cherrypy.server.thread_pool)
    print_report(size_report())


#                         modpython and other WSGI                         # 
Example #7
Source File: _cpchecker.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def _populate_known_types(self):
        b = [x for x in vars(builtins).values()
             if type(x) is type(str)]

        def traverse(obj, namespace):
            for name in dir(obj):
                # Hack for 3.2's warning about body_params
                if name == 'body_params':
                    continue
                vtype = type(getattr(obj, name, None))
                if vtype in b:
                    self.known_config_types[namespace + '.' + name] = vtype

        traverse(cherrypy.request, 'request')
        traverse(cherrypy.response, 'response')
        traverse(cherrypy.server, 'server')
        traverse(cherrypy.engine, 'engine')
        traverse(cherrypy.log, 'log') 
Example #8
Source File: _cperror.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def _be_ie_unfriendly(status):
    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
    # (by adding whitespace).
    # See http://support.microsoft.com/kb/q218155/
    s = _ie_friendly_error_sizes.get(status, 0)
    if s:
        s += 1
        # Since we are issuing an HTTP error status, we assume that
        # the entity is short, and we should just collapse it.
        content = response.collapse_body()
        content_length = len(content)
        if content_length and content_length < s:
            # IN ADDITION: the response must be written to IE
            # in one chunk or it will still get replaced! Bah.
            content = content + (b' ' * (s - content_length))
        response.body = content
        response.headers['Content-Length'] = str(len(content)) 
Example #9
Source File: _cperror.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
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.
        """
        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 = None
        if cherrypy.serving.request.show_tracebacks:
            tb = format_exc()

        response.headers.pop('Content-Length', None)

        content = self.get_error_page(self.status, traceback=tb,
                                      message=self._message)
        response.body = content

        _be_ie_unfriendly(self.code) 
Example #10
Source File: _cperror.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def clean_headers(status):
    """Remove any headers which should not apply to an error response."""
    response = cherrypy.serving.response

    # Remove headers which applied to the original content,
    # but do not apply to the error page.
    respheaders = response.headers
    for key in ['Accept-Ranges', 'Age', 'ETag', 'Location', 'Retry-After',
                'Vary', 'Content-Encoding', 'Content-Length', 'Expires',
                '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
        # with a byte-range-resp-spec of "*". The instance-length
        # specifies the current length of the selected resource.
        # A response with status code 206 (Partial Content) MUST NOT
        # include a Content-Range field with a byte-range- resp-spec of "*".
        if 'Content-Range' in respheaders:
            del respheaders['Content-Range'] 
Example #11
Source File: benchmark.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def run_standard_benchmarks():
    print('')
    print('Client Thread Report (1000 requests, 14 byte response body, '
          '%s server threads):' % cherrypy.server.thread_pool)
    print_report(thread_report())

    print('')
    print('Client Thread Report (1000 requests, 14 bytes via staticdir, '
          '%s server threads):' % cherrypy.server.thread_pool)
    print_report(thread_report('%s/static/index.html' % SCRIPT_NAME))

    print('')
    print('Size Report (1000 requests, 50 client threads, '
          '%s server threads):' % cherrypy.server.thread_pool)
    print_report(size_report())


#                         modpython and other WSGI                         # 
Example #12
Source File: xmlrpcutil.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def _set_response(body):
    # The XML-RPC spec (http://www.xmlrpc.com/spec) says:
    # "Unless there's a lower-level error, always return 200 OK."
    # Since Python's xmlrpclib interprets a non-200 response
    # as a "Protocol Error", we'll just return 200 every time.
    response = cherrypy.response
    response.status = '200 OK'
    response.body = ntob(body, 'utf-8')
    response.headers['Content-Type'] = 'text/xml'
    response.headers['Content-Length'] = len(body) 
Example #13
Source File: _cperror.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
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
    # (by adding whitespace).
    # See http://support.microsoft.com/kb/q218155/
    s = _ie_friendly_error_sizes.get(status, 0)
    if s:
        s += 1
        # Since we are issuing an HTTP error status, we assume that
        # the entity is short, and we should just collapse it.
        content = response.collapse_body()
        l = len(content)
        if l and l < s:
            # IN ADDITION: the response must be written to IE
            # in one chunk or it will still get replaced! Bah.
            content = content + (ntob(' ') * (s - l))
        response.body = content
        response.headers['Content-Length'] = str(len(content)) 
Example #14
Source File: _cperror.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
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
    for key in ['Accept-Ranges', 'Age', 'ETag', 'Location', 'Retry-After',
                'Vary', 'Content-Encoding', 'Content-Length', 'Expires',
                '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
        # with a byte-range-resp-spec of "*". The instance-length
        # specifies the current length of the selected resource.
        # A response with status code 206 (Partial Content) MUST NOT
        # include a Content-Range field with a byte-range- resp-spec of "*".
        if 'Content-Range' in respheaders:
            del respheaders['Content-Range'] 
Example #15
Source File: _cperror.py    From opsbro with MIT License 6 votes vote down vote up
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
    # (by adding whitespace).
    # See http://support.microsoft.com/kb/q218155/
    s = _ie_friendly_error_sizes.get(status, 0)
    if s:
        s += 1
        # Since we are issuing an HTTP error status, we assume that
        # the entity is short, and we should just collapse it.
        content = response.collapse_body()
        l = len(content)
        if l and l < s:
            # IN ADDITION: the response must be written to IE
            # in one chunk or it will still get replaced! Bah.
            content = content + (ntob(" ") * (s - l))
        response.body = content
        response.headers['Content-Length'] = str(len(content)) 
Example #16
Source File: _cperror.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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.
        """
        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 = None
        if cherrypy.serving.request.show_tracebacks:
            tb = format_exc()

        response.headers.pop('Content-Length', None)

        content = self.get_error_page(self.status, traceback=tb,
                                      message=self._message)
        response.body = content

        _be_ie_unfriendly(self.code) 
Example #17
Source File: _cperror.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _be_ie_unfriendly(status):
    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
    # (by adding whitespace).
    # See http://support.microsoft.com/kb/q218155/
    s = _ie_friendly_error_sizes.get(status, 0)
    if s:
        s += 1
        # Since we are issuing an HTTP error status, we assume that
        # the entity is short, and we should just collapse it.
        content = response.collapse_body()
        content_length = len(content)
        if content_length and content_length < s:
            # IN ADDITION: the response must be written to IE
            # in one chunk or it will still get replaced! Bah.
            content = content + (b' ' * (s - content_length))
        response.body = content
        response.headers['Content-Length'] = str(len(content)) 
Example #18
Source File: _cperror.py    From opsbro with MIT License 6 votes vote down vote up
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
    for key in ["Accept-Ranges", "Age", "ETag", "Location", "Retry-After",
                "Vary", "Content-Encoding", "Content-Length", "Expires",
                "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
        # with a byte-range-resp-spec of "*". The instance-length
        # specifies the current length of the selected resource.
        # A response with status code 206 (Partial Content) MUST NOT
        # include a Content-Range field with a byte-range- resp-spec of "*".
        if "Content-Range" in respheaders:
            del respheaders["Content-Range"] 
Example #19
Source File: _cpchecker.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _populate_known_types(self):
        b = [x for x in vars(builtins).values()
             if type(x) is type(str)]

        def traverse(obj, namespace):
            for name in dir(obj):
                # Hack for 3.2's warning about body_params
                if name == 'body_params':
                    continue
                vtype = type(getattr(obj, name, None))
                if vtype in b:
                    self.known_config_types[namespace + '.' + name] = vtype

        traverse(cherrypy.request, 'request')
        traverse(cherrypy.response, 'response')
        traverse(cherrypy.server, 'server')
        traverse(cherrypy.engine, 'engine')
        traverse(cherrypy.log, 'log') 
Example #20
Source File: benchmark.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_standard_benchmarks():
    print('')
    print('Client Thread Report (1000 requests, 14 byte response body, '
          '%s server threads):' % cherrypy.server.thread_pool)
    print_report(thread_report())

    print('')
    print('Client Thread Report (1000 requests, 14 bytes via staticdir, '
          '%s server threads):' % cherrypy.server.thread_pool)
    print_report(thread_report('%s/static/index.html' % SCRIPT_NAME))

    print('')
    print('Size Report (1000 requests, 50 client threads, '
          '%s server threads):' % cherrypy.server.thread_pool)
    print_report(size_report())


#                         modpython and other WSGI                         # 
Example #21
Source File: xmlrpcutil.py    From opsbro with MIT License 5 votes vote down vote up
def _set_response(body):
    # The XML-RPC spec (http://www.xmlrpc.com/spec) says:
    # "Unless there's a lower-level error, always return 200 OK."
    # Since Python's xmlrpclib interprets a non-200 response
    # as a "Protocol Error", we'll just return 200 every time.
    response = cherrypy.response
    response.status = '200 OK'
    response.body = ntob(body, 'utf-8')
    response.headers['Content-Type'] = 'text/xml'
    response.headers['Content-Length'] = len(body) 
Example #22
Source File: benchmark.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
def run(self, method, path, query_string, protocol, headers, rfile):
        cherrypy.response.status = "200 OK"
        cherrypy.response.header_list = [("Content-Type", 'text/html'),
                                         ("Server", "Null CherryPy"),
                                         ("Date", httputil.HTTPDate()),
                                         ("Content-Length", "0"),
                                         ]
        cherrypy.response.body = [""]
        return cherrypy.response 
Example #23
Source File: xmlrpcutil.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
def _set_response(body):
    # The XML-RPC spec (http://www.xmlrpc.com/spec) says:
    # "Unless there's a lower-level error, always return 200 OK."
    # Since Python's xmlrpclib interprets a non-200 response
    # as a "Protocol Error", we'll just return 200 every time.
    response = cherrypy.response
    response.status = '200 OK'
    response.body = ntob(body, 'utf-8')
    response.headers['Content-Type'] = 'text/xml'
    response.headers['Content-Length'] = len(body) 
Example #24
Source File: _cperror.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
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 = None
        if cherrypy.serving.request.show_tracebacks:
            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) 
Example #25
Source File: _cperror.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
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")
            #  3. a URL relative to the current path
            # Note that any query string in cherrypy.request is discarded.
            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
        if status is None:
            if request.protocol >= (1, 1):
                status = 303
            else:
                status = 302
        else:
            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) 
Example #26
Source File: xmlrpcutil.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def respond(body, encoding='utf-8', allow_none=0):
    """Construct HTTP response body."""
    if not isinstance(body, XMLRPCFault):
        body = (body,)

    _set_response(
        xmlrpc_dumps(
            body, methodresponse=1,
            encoding=encoding,
            allow_none=allow_none
        )
    ) 
Example #27
Source File: benchmark.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def run(self, method, path, query_string, protocol, headers, rfile):
        cherrypy.response.status = '200 OK'
        cherrypy.response.header_list = [('Content-Type', 'text/html'),
                                         ('Server', 'Null CherryPy'),
                                         ('Date', httputil.HTTPDate()),
                                         ('Content-Length', '0'),
                                         ]
        cherrypy.response.body = ['']
        return cherrypy.response 
Example #28
Source File: xmlrpcutil.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def on_error(*args, **kwargs):
    """Construct HTTP response body for an error response."""
    body = str(sys.exc_info()[1])
    _set_response(xmlrpc_dumps(XMLRPCFault(1, body))) 
Example #29
Source File: xmlrpcutil.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def respond(body, encoding='utf-8', allow_none=0):
    """Construct HTTP response body."""
    if not isinstance(body, XMLRPCFault):
        body = (body,)

    _set_response(
        xmlrpc_dumps(
            body, methodresponse=1,
            encoding=encoding,
            allow_none=allow_none
        )
    ) 
Example #30
Source File: xmlrpcutil.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def on_error(*args, **kwargs):
    """Construct HTTP response body for an error response."""
    body = str(sys.exc_info()[1])
    _set_response(xmlrpc_dumps(XMLRPCFault(1, body)))