How do I find mime-type in Python
Question: I am trying out some CGI-scripting in Python. If a request come to my python
script, how do I find the mime-type of the filetype?

UPDATE: Adding more info Some images for now, adderess/image.jpg. But if I
understand mime-type is part of the headers that the web-browsers sends,
right? So how do I read these headers?


Answer: You have two options. If your lucky the client can determine the mimetype of
the file and it can be included in the form post. Usually this is with the
value of the an input element whose name is "filetype" or something similar.

Otherwise you can guess the mimetype from the file extension on the server.
This is somewhat dependent on how up-to-date the mimetypes module is. Note
that you can add types or override types in the module. Then you use the
"guess_type" function that interprets the mimetype from the filename's
extension.

    
    
    import mimetypes
    mimetypes.add_type('video/webm','.webm')
    
    ...
    
        mimetypes.guess_type(filename)
    

UPDATE: If I remember correctly you can get the client's interpretation of the
mimetype from the "Content-Type" header. A lot of the time this turns out to
be 'application/octet-stream' which is almost useless.

So assuming your using the cgi module, and you're uploading files with the
usual multipart form, the browser is going to guess the mimetype for you. It
seems to do a decent job of it, and it gets passed through to the form.type
parameter. So you can do something like this:

    
    
    import cgi
    form = cgi.FieldStorage()
    files_types = {};
    if form.type == 'multipart/form-data':
        for part in form.keys():
            files_types[form[part].filename] = form[part].type
    else:
        files_types[form.filename] = form.type
    

