How can I show content type images using Python's BaseHTTPServerRequestHandler do_GET method?

I use BaseHTTPServer to serve web content. I can use the text types "text / html" or "text / css" or even "text / js" and it is displayed on the browser side. But when I try

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

for the .png file, it does not appear at all.

Here is an example:

  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 is not like an image when I mark it on the client side. It looks like a broken image.

Any ideas?

+4
source share
3 answers

You opened the file in text mode instead of binary mode. Any newlines are likely to be corrupted. Use this instead:

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

Try using 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 information.

+3
source

you can always open the file as binary; -)

Perhaps you can look at SimpleHTTPServer.py in 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 uses 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 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:

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

+1
source

Source: https://habr.com/ru/post/1343507/


All Articles