How do I serve image Content-types with Python BaseHTTPServerRequestHandler do_GET method?

我们两清 提交于 2019-12-03 09:07:27

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')

Try to use SimpleHTTPServer

class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    """modify Content-type """
    def guess_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.

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['']

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!