How to use the cherrypy._cpcompat.ntob 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 / cherrypy / py2 / cherrypy / lib / httputil.py View on Github external
def encode(self, v):
        """Return the given header name or value, encoded for HTTP output."""
        for enc in self.encodings:
            try:
                return v.encode(enc)
            except UnicodeEncodeError:
                continue
        
        if self.protocol == (1, 1) and self.use_rfc_2047:
            # Encode RFC-2047 TEXT 
            # (e.g. u"\u8200" -> "=?utf-8?b?6IiA?="). 
            # We do our own here instead of using the email module
            # because we never want to fold lines--folding has
            # been deprecated by the HTTP working group.
            v = b2a_base64(v.encode('utf-8'))
            return (ntob('=?utf-8?b?') + v.strip(ntob('\n')) + ntob('?='))
        
        raise ValueError("Could not encode header part %r using "
                         "any of the encodings %r." %
                         (v, self.encodings))
github cherrypy / cherrypy / cherrypy / lib / xmlrpcutil.py View on Github external
def _set_response(body):
    """Set up HTTP status, headers and body within CherryPy."""
    # The XML-RPC spec (http://www.xmlrpc.com/spec) says:
    # "Unless there's a lower-level error, always return 200 OK."
    # Since Python's xmlrpc_client 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)
github 05sonicblue / GamezServer / cherrypy / lib / static.py View on Github external
def file_ranges():
                    # Apache compatibility:
                    yield ntob("\r\n")

                    for start, stop in r:
                        if debug:
                            cherrypy.log(
                                'Multipart; start: %r, stop: %r' % (
                                    start, stop),
                                'TOOLS.STATIC')
                        yield ntob("--" + boundary, 'ascii')
                        yield ntob("\r\nContent-type: %s" % content_type,
                                   'ascii')
                        yield ntob(
                            "\r\nContent-range: bytes %s-%s/%s\r\n\r\n" % (
                                start, stop - 1, content_length),
                            'ascii')
                        fileobj.seek(start)
                        gen = file_generator_limited(fileobj, stop - start)
                        for chunk in gen:
                            yield chunk
                        yield ntob("\r\n")
                    # Final boundary
                    yield ntob("--" + boundary + "--", 'ascii')

                    # Apache compatibility:
                    yield ntob("\r\n")
                response.body = file_ranges()
github kodi-community-addons / plugin.audio.spotify / resources / libs / cherrypy / _cperror.py View on Github external
as-is to the body.
    """

    # The whole point of this function is to be a last line-of-defense
    # in handling errors. That is, it must not raise any errors itself;
    # it cannot be allowed to fail. Therefore, don't add to it!
    # In particular, don't call any other CP functions.

    body = ntob("Unrecoverable error in the server.")
    if extrabody is not None:
        if not isinstance(extrabody, bytes):
            extrabody = extrabody.encode('utf-8')
        body += ntob("\n") + extrabody

    return (ntob("500 Internal Server Error"),
            [(ntob('Content-Type'), ntob('text/plain')),
             (ntob('Content-Length'), ntob(str(len(body)), 'ISO-8859-1'))],
            [body])
github cherrypy / cheroot / py3 / cherrypy / lib / httputil.py View on Github external
def encode(self, v):
        """Return the given header name or value, encoded for HTTP output."""
        for enc in self.encodings:
            try:
                return v.encode(enc)
            except UnicodeEncodeError:
                continue
        
        if self.protocol == (1, 1) and self.use_rfc_2047:
            # Encode RFC-2047 TEXT 
            # (e.g. u"\u8200" -> "=?utf-8?b?6IiA?="). 
            # We do our own here instead of using the email module
            # because we never want to fold lines--folding has
            # been deprecated by the HTTP working group.
            v = b2a_base64(v.encode('utf-8'))
            return (ntob('=?utf-8?b?') + v.strip(ntob('\n')) + ntob('?='))
        
        raise ValueError("Could not encode header part %r using "
                         "any of the encodings %r." %
                         (v, self.encodings))
github CouchPotato / CouchPotatoV1 / cherrypy / _cperror.py View on Github external
response.headers['Content-Type'] = "text/html;charset=utf-8"
            # "The ... URI SHOULD be given by the Location field
            # in the response."
            response.headers['Location'] = self.urls[0]
            
            # "Unless the request method was HEAD, the entity of the response
            # SHOULD contain a short hypertext note with a hyperlink to the
            # new URI(s)."
            msg = {300: "This resource can be found at <a href="%s">%s</a>.",
                   301: "This resource has permanently moved to <a href="%s">%s</a>.",
                   302: "This resource resides temporarily at <a href="%s">%s</a>.",
                   303: "This resource can be found at <a href="%s">%s</a>.",
                   307: "This resource has moved temporarily to <a href="%s">%s</a>.",
                   }[status]
            msgs = [msg % (u, u) for u in self.urls]
            response.body = ntob("<br>\n".join(msgs), 'utf-8')
            # Previous code may have set C-L, so we have to reset it
            # (allow finalize to set it).
            response.headers.pop('Content-Length', None)
        elif status == 304:
            # Not Modified.
            # "The response MUST include the following header fields:
            # Date, unless its omission is required by section 14.18.1"
            # The "Date" header should have been set in Response.__init__
            
            # "...the response SHOULD NOT include other entity-headers."
            for key in ('Allow', 'Content-Encoding', 'Content-Language',
                        'Content-Length', 'Content-Location', 'Content-MD5',
                        'Content-Range', 'Content-Type', 'Expires',
                        'Last-Modified'):
                if key in response.headers:
                    del response.headers[key]
github cylc / cylc-flow / lib / cherrypy / _cprequest.py View on Github external
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 &lt; 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,
github rembo10 / headphones / lib / cherrypy / _cpreqbody.py View on Github external
def read_lines_to_boundary(self, fp_out=None):
        """Read bytes from self.fp and return or write them to a file.

        If the 'fp_out' argument is None (the default), all bytes read are
        returned in a single byte string.

        If the 'fp_out' argument is not None, it must be a file-like
        object that supports the 'write' method; all bytes read will be
        written to the fp, and that fp is returned.
        """
        endmarker = self.boundary + ntob("--")
        delim = ntob("")
        prev_lf = True
        lines = []
        seen = 0
        while True:
            line = self.fp.readline(1 &lt;&lt; 16)
            if not line:
                raise EOFError("Illegal end of multipart body.")
            if line.startswith(ntob("--")) and prev_lf:
                strippedline = line.strip()
                if strippedline == self.boundary:
                    break
                if strippedline == endmarker:
                    self.fp.finish()
                    break