Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a content-type of a file in Python? (with url..)

Suppose I haev a video file:

http://mydomain.com/thevideofile.mp4

How do I get the header and the content-type of this file? With Python. But , I don't want to download the entire file. i want it to return:

video/mp4

Edit: this is what I did. What do you think?

f = urllib2.urlopen(url)
    params['mime'] =  f.headers['content-type']
like image 788
TIMEX Avatar asked Jan 27 '10 00:01

TIMEX


People also ask

How does Python handle URL?

Urllib package is the URL handling module for python. It is used to fetch URLs (Uniform Resource Locators). It uses the urlopen function and is able to fetch URLs using a variety of different protocols.

What is URL open in Python?

This Python module defines the classes and functions that help in the URL actions. The urlopen() function provides a fairly simple interface. It is capable of retrieving URLs with a variety of protocols.


2 Answers

Like so:

>>> import httplib
>>> conn = httplib.HTTPConnection("mydomain.com")
>>> conn.request("HEAD", "/thevideofile.mp4")
>>> res = conn.getresponse()
>>> print res.getheaders()

That will only download and print the headers because it is making a HEAD request:

Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.

(via Wikipedia)

like image 152
Brian McKenna Avatar answered Oct 05 '22 10:10

Brian McKenna


This is a higher level answer than Brian's. Using the urllib machinery has the usual advantages such as handling redirects automatically and so on.

import urllib2

class HeadRequest(urllib2.Request):
    def get_method(self):
        return "HEAD"

url = "http://mydomain.com/thevideofile.mp4"
head = urllib2.urlopen(HeadRequest(url))
head.read()          # This will return empty string and closes the connection
print head.headers.maintype
print head.headers.subtype
print head.headers.type
like image 44
John La Rooy Avatar answered Oct 05 '22 09:10

John La Rooy