check if a URL to an image is up and exists in Python
Question: I am making a website. I want to check from the server whether the link that
the user submitted is actually an image that exists.


Answer: This is one way that is quick:

It doesn't really verify that is really an image file, it just guesses based
on file extention and then checks that the url exists. If you really need to
verify that the data returned from the url is actually an image (for security
reasons) then this solution would not work.

    
    
    import mimetypes, urllib2
    
    def is_url_image(url):    
        mimetype,encoding = mimetypes.guess_type(url)
        return (mimetype and mimetype.startswith('image'))
    
    def check_url(url):
        """Returns True if the url returns a response code between 200-300,
           otherwise return False.
        """
        try:
            headers={
                "Range": "bytes=0-10",
                "User-Agent": "MyTestAgent",
                "Accept":"*/*"
            }
    
            req = urllib2.Request(url, headers=headers)
            response = urllib2.urlopen(req)
            return response.code in range(200, 209)
        except Exception, ex:
            return False
    
    def is_image_and_ready(url):
        return is_url_image(url) and check_url(url)
    

