Skip to content Skip to sidebar Skip to footer

How Do I Serve Image Content-types With Python Basehttpserverrequesthandler Do_get Method?

I'm using BaseHTTPServer to serve web content. I can serve Content-types 'text/html' or 'text/css' or even 'text/js' and it renders on the browser side. But when I try to self.send

Solution 1:

You've opened the file in text mode instead of binary mode. Any newline characters are likely to get messed up. Use this instead:

f = open(curdir + sep + self.path, 'rb')

Solution 2:

Try to use SimpleHTTPServer

classMyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    """modify Content-type """defguess_type(self, path):
        mimetype = SimpleHTTPServer.SimpleHTTPRequestHandler.guess_type(
            self, path
            )
        if mimetype == 'application/octet-stream':
            if path.endswith('manifest'):
                mimetype = 'text/cache-manifest'return mimetype

see /usr/lib/python2.7/SimpleHTTPServer.py for more infomation.

Solution 3:

you can always open the file as binary ;-)

Maybe you could look at SimpleHTTPServer.py at this part of the code:

    ctype = self.guess_type(path)
    try:
        # Always read in binary mode. Opening files in text mode may cause
        # newline translations, making the actual size of the content
        # transmitted *less* than the content-length!
        f = open(path, 'rb')
    except IOError:
        self.send_error(404, "File not found")
        return None

Then if you look at def guess_type(self, path): its very simple, it use the file "extension" ;-)

    Return value is a string of the form type/subtype,
    usable for a MIME Content-type header.

    The default implementation looks the file's extension
    up in the table self.extensions_map, using application/octet-stream
    as a default; however it would be permissible (if
    slow) to look inside the data to make a better guess.

Just in case, the code is:

    base, ext = posixpath.splitext(path)
    if ext in self.extensions_map:
        return self.extensions_map[ext]
    ext = ext.lower()
    if ext in self.extensions_map:
        return self.extensions_map[ext]
    else:
        return self.extensions_map['']

Post a Comment for "How Do I Serve Image Content-types With Python Basehttpserverrequesthandler Do_get Method?"