如何使用Python BaseHTTPServerRequestHandler do_GET方法提供图像内容类型?

时间:2011-03-13 03:32:32

标签: python basehttpserver

我正在使用BaseHTTPServer来提供网络内容。我可以提供内容类型'text / html'或'text / css'甚至'text / js',并在浏览器端呈现。但是当我试着

self.send_header('Content-type', 'image/png')

对于.png文件,它根本不会渲染。

以下是一个示例:

                    if self.path.endswith(".js"):
                            f = open(curdir + sep + self.path)
                            self.send_response(200)
                            self.send_header('Content-type',        'text/javascript')
                            self.end_headers()
                            self.wfile.write(f.read())
                            f.close()
                            return

这适用于javascript

                    if self.path.endswith(".png"):
                            f=open(curdir + sep + self.path)
                            self.send_response(200)
                            self.send_header('Content-type',        'image/png')
                            self.end_headers()
                            self.wfile.write(f.read())
                            f.close()
                            return

当我为客户端标记时,这似乎不会呈现图像内容。它看起来像是一张破碎的图像。

有什么想法吗?

3 个答案:

答案 0 :(得分:9)

您已在文本模式而不是二进制模式下打开文件。任何换行符都可能搞砸了。请改用:

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

答案 1 :(得分:3)

尝试使用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

有关详细信息,请参阅/usr/lib/python2.7/SimpleHTTPServer.py。

答案 2 :(得分:1)

您始终可以将文件打开为二进制文件; - )

也许您可以在代码的这一部分查看SimpleHTTPServer.py:

    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

然后,如果你看 def guess_type(self,path):它非常简单,它使用文件" 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.

以防万一,代码为:


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