How to use the cherrypy.serving.response function in CherryPy

To help you get started, we’ve selected a few CherryPy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github oaubert / advene / lib / cherrypy / lib / cptools.py View on Github external
def do_check(self):
        """Assert username. Raise redirect, or return True if request handled.
        """
        sess = cherrypy.session
        request = cherrypy.serving.request
        response = cherrypy.serving.response

        username = sess.get(self.session_key)
        if not username:
            sess[self.session_key] = username = self.anonymous()
            if self.debug:
                cherrypy.log(
                    'No session[username], trying anonymous', 'TOOLS.SESSAUTH')
        if not username:
            url = cherrypy.url(qs=request.query_string)
            if self.debug:
                cherrypy.log('No username, routing to login_screen with '
                             'from_page %r' % url, 'TOOLS.SESSAUTH')
            response.body = self.login_screen(url)
            if "Content-Length" in response.headers:
                # Delete Content-Length header so finalize() recalcs it.
                del response.headers["Content-Length"]
github paolodoz / timesheet / cherrypy / lib / sessions.py View on Github external
"session cookie" which expires when the browser is closed.

    domain
        the cookie domain.

    secure
        if False (the default) the cookie 'secure' value will not
        be set. If True, the cookie 'secure' value will be set (to 1).

    httponly
        If False (the default) the cookie 'httponly' value will not be set.
        If True, the cookie 'httponly' value will be set (to 1).

    """
    # Set response cookie
    cookie = cherrypy.serving.response.cookie
    cookie[name] = cherrypy.serving.session.id
    cookie[name]['path'] = (path or cherrypy.serving.request.headers.get(path_header)
                            or '/')
    
    # We'd like to use the "max-age" param as indicated in
    # http://www.faqs.org/rfcs/rfc2109.html but IE doesn't
    # save it to disk and the session is lost if people close
    # the browser. So we have to use the old "expires" ... sigh ...
##    cookie[name]['max-age'] = timeout * 60
    if timeout:
        e = time.time() + (timeout * 60)
        cookie[name]['expires'] = httputil.HTTPDate(e)
    if domain is not None:
        cookie[name]['domain'] = domain
    if secure:
        cookie[name]['secure'] = 1
github rembo10 / headphones / lib / cherrypy / lib / cpstats.py View on Github external
def record_stop(self, uriset=None, slow_queries=1.0, slow_queries_count=100,
                    debug=False, **kwargs):
        """Record the end of a request."""
        resp = cherrypy.serving.response
        w = appstats['Requests'][threading._get_ident()]
        
        r = cherrypy.request.rfile.bytes_read
        w['Bytes Read'] = r
        appstats['Total Bytes Read'] += r
        
        if resp.stream:
            w['Bytes Written'] = 'chunked'
        else:
            cl = int(resp.headers.get('Content-Length', 0))
            w['Bytes Written'] = cl
            appstats['Total Bytes Written'] += cl
        
        w['Response Status'] = getattr(resp, 'output_status', None) or resp.status
        
        w['End Time'] = time.time()
github kodi-community-addons / plugin.audio.spotify / resources / libs / cherrypy / _cpwsgi.py View on Github external
def __init__(self, environ, start_response, cpapp):
        self.cpapp = cpapp
        try:
            if six.PY2:
                if environ.get(ntou('wsgi.version')) == (ntou('u'), 0):
                    environ = downgrade_wsgi_ux_to_1x(environ)
            self.environ = environ
            self.run()

            r = _cherrypy.serving.response

            outstatus = r.output_status
            if not isinstance(outstatus, bytes):
                raise TypeError("response.output_status is not a byte string.")

            outheaders = []
            for k, v in r.header_list:
                if not isinstance(k, bytes):
                    raise TypeError(
                        "response.header_list key %r is not a byte string." %
                        k)
                if not isinstance(v, bytes):
                    raise TypeError(
                        "response.header_list value %r is not a byte string." %
                        v)
                outheaders.append((k, v))
github h3llrais3r / Auto-Subliminal / lib / cherrypy / _cprequest.py View on Github external
A list of (name, value) tuples.

        rfile
            A file-like object containing the HTTP request entity.

        When run() is done, the returned object should have 3 attributes:

          * status, e.g. "200 OK"
          * header_list, a list of (name, value) tuples
          * body, an iterable yielding strings

        Consumer code (HTTP servers) should then access these response
        attributes to build the outbound stream.

        """
        response = cherrypy.serving.response
        self.stage = 'run'
        try:
            self.error_response = cherrypy.HTTPError(500).set_response

            self.method = method
            path = path or '/'
            self.query_string = query_string or ''
            self.params = {}

            # Compare request and server HTTP protocol versions, in case our
            # server does not support the requested protocol. Limit our output
            # to min(req, server). We want the following output:
            #     request    server     actual written   supported response
            #     protocol   protocol  response protocol    feature set
            # a     1.0        1.0           1.0                1.0
            # b     1.0        1.1           1.1                1.0
github naparuba / opsbro / opsbro / misc / internalcherrypy / cherrypy / _cperror.py View on Github external
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.
github kodi-community-addons / plugin.audio.spotify / resources / libs / cherrypy / _cperror.py View on Github external
'return a bytestring, six.text_typeing or an '
                            'iterator - returned object of type %s.'
                            % (type(result).__name__))
                    return result
            else:
                # Load the template from this path.
                template = tonative(open(error_page, 'rb').read())
        except:
            e = _format_exception(*_exc_info())[-1]
            m = kwargs['message']
            if m:
                m += "<br>"
            m += "In addition, the custom error page failed:\n<br>%s" % e
            kwargs['message'] = m

    response = cherrypy.serving.response
    response.headers['Content-Type'] = "text/html;charset=utf-8"
    result = template % kwargs
    return result.encode('utf-8')
github h3llrais3r / Auto-Subliminal / lib / cherrypy / lib / sessions.py View on Github external
"session cookie" which expires when the browser is closed.

    domain
        the cookie domain.

    secure
        if False (the default) the cookie 'secure' value will not
        be set. If True, the cookie 'secure' value will be set (to 1).

    httponly
        If False (the default) the cookie 'httponly' value will not be set.
        If True, the cookie 'httponly' value will be set (to 1).

    """
    # Set response cookie
    cookie = cherrypy.serving.response.cookie
    cookie[name] = cherrypy.serving.session.id
    cookie[name]['path'] = (
        path or
        cherrypy.serving.request.headers.get(path_header) or
        '/'
    )

    if timeout:
        cookie[name]['max-age'] = timeout * 60
        _add_MSIE_max_age_workaround(cookie[name], timeout)
    if domain is not None:
        cookie[name]['domain'] = domain
    if secure:
        cookie[name]['secure'] = 1
    if httponly:
        if not cookie[name].isReservedKey('httponly'):
github cylc / cylc-flow / lib / cherrypy / lib / encoding.py View on Github external
def find_acceptable_charset(self):
        request = cherrypy.serving.request
        response = cherrypy.serving.response

        if self.debug:
            cherrypy.log('response.stream %r' %
                         response.stream, 'TOOLS.ENCODE')
        if response.stream:
            encoder = self.encode_stream
        else:
            encoder = self.encode_string
            if "Content-Length" in response.headers:
                # Delete Content-Length header so finalize() recalcs it.
                # Encoded strings may be of different lengths from their
                # unicode equivalents, and even from each other. For example:
                # >>> t = u"\u7007\u3040"
                # >>> len(t)
                # 2
                # >>> len(t.encode("UTF-8"))
github fuzeman / Spotify2.bundle / Contents / Libraries / Shared / cherrypy / lib / caching.py View on Github external
* Pragma: no-cache
            * Cache-Control': no-cache, must-revalidate

    force
        If False, the following headers are checked:

            * Etag
            * Last-Modified
            * Age
            * Expires

        If any are already present, none of the above response headers are set.

    """

    response = cherrypy.serving.response
    headers = response.headers

    cacheable = False
    if not force:
        # some header names that indicate that the response can be cached
        for indicator in ('Etag', 'Last-Modified', 'Age', 'Expires'):
            if indicator in headers:
                cacheable = True
                break

    if not cacheable and not force:
        if debug:
            cherrypy.log('request is not cacheable', 'TOOLS.EXPIRES')
    else:
        if debug:
            cherrypy.log('request is cacheable', 'TOOLS.EXPIRES')