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

Brandon Runyon picture Brandon Runyon · Mar 13, 2011 · Viewed 11.1k times · Source

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_header('Content-type', 'image/png')

for a .png file, it doesn't render at all.

Here is a sample:

                    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

this works great for 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

this doesn't seem to render the image content when I mark it up for client side. It appears as a broken image.

Any ideas?

Answer

Liquid_Fire picture Liquid_Fire · Mar 13, 2011

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