Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Python http.server use correct content-type header for webp images

Trying to run a very simple local python webserver to serve a directory with some images in different formats like png, jpg and webp.

python3 -m http.server -d /path/webdir 8090

Unfortunately, webp images are served with the wrong header: Content-type: application/octet-stream instead of Content-type: image/webp

How can I fix this? (still using a oneliner to start the python webserver)

Yes I know php is doing it fine:

 php -t /path/webdir -S  localhost:8090
like image 763
Janghou Avatar asked Oct 21 '25 05:10

Janghou


1 Answers

Base on source code it uses module mimetypes to guess type

import mimetypes  

print( mimetypes.guess_type('name.webp') )

Result

(None, None)

This module uses some files in system to guess type

print( mimetypes.knownfiles )

Result on Linux Mint 20 (based on Ubuntu 20.04)

[
 '/etc/mime.types', 
 '/etc/httpd/mime.types', 
 '/etc/httpd/conf/mime.types', 
 '/etc/apache/mime.types', 
 '/etc/apache2/mime.types', 
 '/usr/local/etc/httpd/conf/mime.types', 
 '/usr/local/lib/netscape/mime.types', 
 '/usr/local/etc/httpd/conf/mime.types', 
 '/usr/local/etc/mime.types'
]

If I add line in one of these files - ie. /etc/mime.types

image/webp                  webp

Then mimetypes.guess_type('name.webp') gives me

('image/webp', None)

and I think it should resolve proble with your server.


EDIT:

I tested python3 -m http.server before and after adding line in /etc/mime.types and it resolved problem on my Linux.

like image 157
furas Avatar answered Oct 23 '25 20:10

furas