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']
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.
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With