How to use the cherrypy.serving 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 cherrypy / cheroot / py3 / cherrypy / _cplogging.py View on Github external
See http://httpd.apache.org/docs/2.0/logs.html#combined for format
        details.
        
        CherryPy calls this automatically for you. Note there are no arguments;
        it collects the data itself from
        :class:`cherrypy.request`.
        
        Like Apache started doing in 2.0.46, non-printable and other special
        characters in %r (and we expand that to all parts) are escaped using
        \\xhh sequences, where hh stands for the hexadecimal representation
        of the raw byte. Exceptions from this rule are " and \\, which are
        escaped by prepending a backslash, and all whitespace characters,
        which are written in their C-style notation (\\n, \\t, etc).
        """
        request = cherrypy.serving.request
        remote = request.remote
        response = cherrypy.serving.response
        outheaders = response.headers
        inheaders = request.headers
        if response.output_status is None:
            status = "-"
        else:
            status = response.output_status.split(ntob(" "), 1)[0]
            if _py3k:
                status = status.decode('ISO-8859-1')
        
        atoms = {'h': remote.name or remote.ip,
                 'l': '-',
                 'u': getattr(request, "login", None) or "-",
                 't': self.time(),
                 'r': request.request_line,
github paolodoz / timesheet / 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 cylc / cylc-flow / lib / cherrypy / lib / auth_digest.py View on Github external
# The choice of ten minutes' lifetime for nonce is somewhat
                    # arbitrary
                    nonce_is_stale = auth.is_nonce_stale(max_age_seconds=600)
                    if not nonce_is_stale:
                        request.login = auth.username
                        if debug:
                            TRACE("authentication of %s successful" %
                                  auth.username)
                        return

    # Respond with 401 status and a WWW-Authenticate header
    header = www_authenticate(
        realm, key, algorithm=algorithm, stale=nonce_is_stale)
    if debug:
        TRACE(header)
    cherrypy.serving.response.headers['WWW-Authenticate'] = header
    raise cherrypy.HTTPError(
        401, "You are not authorized to access that resource")
github cherrypy / cheroot / py3 / cherrypy / _cperror.py View on Github external
kwargs['status'] = "%s %s" % (code, reason)
    if kwargs.get('message') is None:
        kwargs['message'] = message
    if kwargs.get('traceback') is None:
        kwargs['traceback'] = ''
    if kwargs.get('version') is None:
        kwargs['version'] = cherrypy.__version__
    
    for k, v in iteritems(kwargs):
        if v is None:
            kwargs[k] = ""
        else:
            kwargs[k] = _escape(kwargs[k])
    
    # Use a custom template or callable for the error page?
    pages = cherrypy.serving.request.error_page
    error_page = pages.get(code) or pages.get('default')
    if error_page:
        try:
            if hasattr(error_page, '__call__'):
                return error_page(**kwargs)
            else:
                data = open(error_page, 'rb').read()
                return tonative(data) % kwargs
        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
github Southpaw-TACTIC / TACTIC / 3rd_party / python2 / site-packages / cherrypy / lib / cpstats.py View on Github external
def record_start(self):
        """Record the beginning of a request."""
        request = cherrypy.serving.request
        if not hasattr(request.rfile, 'bytes_read'):
            request.rfile = ByteCountWrapper(request.rfile)
            request.body.fp = request.rfile

        r = request.remote

        appstats['Current Requests'] += 1
        appstats['Total Requests'] += 1
        appstats['Requests'][_get_threading_ident()] = {
            'Bytes Read': None,
            'Bytes Written': None,
            # Use a lambda so the ip gets updated by tools.proxy later
            'Client': lambda s: '%s:%s' % (r.ip, r.port),
            'End Time': None,
            'Processing Time': proc_time,
            'Request-Line': request.request_line,
github kovidgoyal / calibre / src / cherrypy / lib / sessions.py View on Github external
def save():
    """Save any changed session data."""
    
    if not hasattr(cherrypy.serving, "session"):
        return
    
    # Guard against running twice
    if hasattr(cherrypy.request, "_sessionsaved"):
        return
    cherrypy.request._sessionsaved = True
    
    if cherrypy.response.stream:
        # If the body is being streamed, we have to save the data
        #   *after* the response has been written out
        cherrypy.request.hooks.attach('on_end_request', cherrypy.session.save)
    else:
        # If the body is not being streamed, we save the data now
        # (so we can release the lock).
        if isinstance(cherrypy.response.body, types.GeneratorType):
            cherrypy.response.collapse_body()
github rembo10 / headphones / lib / cherrypy / lib / caching.py View on Github external
* sets request.cached = True
        * sets request.cacheable = False
        * sets response.headers to the cached values
        * checks the cached Last-Modified response header against the
          current If-(Un)Modified-Since request headers; raises 304
          if necessary.
        * sets response.status and response.body to the cached values
        * returns True

    otherwise:
        * sets request.cached = False
        * sets request.cacheable = True
        * returns False
    """
    request = cherrypy.serving.request
    response = cherrypy.serving.response

    if not hasattr(cherrypy, "_cache"):
        # Make a process-wide Cache object.
        cherrypy._cache = kwargs.pop("cache_class", MemoryCache)()

        # Take all remaining kwargs and set them on the Cache object.
        for k, v in kwargs.items():
            setattr(cherrypy._cache, k, v)
        cherrypy._cache.debug = debug

    # POST, PUT, DELETE should invalidate (delete) the cached copy.
    # See http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.10.
    if request.method in invalid_methods:
        if debug:
            cherrypy.log('request.method %r in invalid_methods %r' %
                         (request.method, invalid_methods), 'TOOLS.CACHING')
github sabnzbd / sabnzbd / cherrypy / _cprequest.py View on Github external
def handle_error(self):
        """Handle the last unanticipated exception. (Core)"""
        try:
            self.hooks.run('before_error_response')
            if self.error_response:
                self.error_response()
            self.hooks.run('after_error_response')
            cherrypy.serving.response.finalize()
        except cherrypy.HTTPRedirect:
            inst = sys.exc_info()[1]
            inst.set_response()
            cherrypy.serving.response.finalize()
github cherrypy / cherrypy / cherrypy / lib / auth.py View on Github external
def check_auth(users, encrypt=None, realm=None):
    """If an authorization header contains credentials, return True or False.
    """
    import_httpauth()
    msg = (
        '`basic_auth` and `digest_auth` tools are deprecated. Use '
        '`auth_basic` and `auth_digest` instead.'
    )
    warnings.warn(msg, DeprecationWarning)
    request = cherrypy.serving.request
    if 'authorization' in request.headers:
        # make sure the provided credentials are correctly set
        ah = httpauth.parseAuthorization(request.headers['authorization'])
        if ah is None:
            raise cherrypy.HTTPError(400, 'Bad Request')

        if not encrypt:
            encrypt = httpauth.DIGEST_AUTH_ENCODERS[httpauth.MD5]

        if hasattr(users, '__call__'):
            try:
                # backward compatibility
                users = users()  # expect it to return a dictionary

                if not isinstance(users, dict):
                    raise ValueError(
github rembo10 / headphones / lib / cherrypy / _cpdispatch.py View on Github external
def __call__(self, path_info):
        """Set handler and config for the current request."""
        request = cherrypy.serving.request
        resource, vpath = self.find_handler(path_info)

        if resource:
            # Set Allow header
            avail = [m for m in dir(resource) if m.isupper()]
            if "GET" in avail and "HEAD" not in avail:
                avail.append("HEAD")
            avail.sort()
            cherrypy.serving.response.headers['Allow'] = ", ".join(avail)

            # Find the subhandler
            meth = request.method.upper()
            func = getattr(resource, meth, None)
            if func is None and meth == "HEAD":
                func = getattr(resource, "GET", None)
            if func:
                # Grab any _cp_config on the subhandler.
                if hasattr(func, "_cp_config"):
                    request.config.update(func._cp_config)

                # Decode any leftover %2F in the virtual_path atoms.
                vpath = [x.replace("%2F", "/") for x in vpath]
                request.handler = LateParamPageHandler(func, *vpath)
            else:
                request.handler = cherrypy.HTTPError(405)